当前位置: 首页 > news >正文

集合框架03:Collection使用(2)

视频链接:13.06 Collection使用(2)_哔哩哔哩_bilibiliicon-default.png?t=O83Ahttps://www.bilibili.com/video/BV1zD4y1Q7Fw?p=6&vd_source=b5775c3a4ea16a5306db9c7c1c1486b5

1.创建Student类

package com.yundait.Demo01;/****学生类* @author zhang*/
public class Student {private String name;private int age;public Student() {}public Student(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}
}

2.创建CollectionDemo02类,实例化Student对象,演示如何在集合中添加、删除、清空、遍历、判断。

package com.yundait.Demo01;import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;public class CollectionDemo02 {public static void main(String[] args) {//新建Collection对象Collection collection = new ArrayList();Student s1 = new Student("张三", 18);Student s2 = new Student("李四", 18);Student s3 = new Student("王五", 18);Student s4 = new Student("赵六", 18);Student s5 = new Student("钱七", 18);//(1)添加数据System.out.println("--------------添加元素-----------");collection.add(s1);collection.add(s2);collection.add(s3);collection.add(s4);collection.add(s5);System.out.println("元素个数" + collection.size());System.out.println(collection.toString());//(2)删除System.out.println("--------------删除元素-----------");collection.remove(s1);System.out.println("删除后元素个数" + collection.size());System.out.println(collection.toString());//(3)清空  注意:删除或清空集合后集合对象并不会消失,因为仅仅删除对象在集合中的地址,真实的对象还在堆中;
//        collection.clear();
//        System.out.println("清空集合后元素个数" + collection.size());//(4)遍历-增强for循环方式System.out.println("--------使用增强for循环遍历---------");for (Object object : collection) {Student s = (Student) object;System.out.println(s);}//(5)遍历-iterator(迭代器)方式:hasNext();  next();  remove()//迭代过程中不能使用Collection的删除方式System.out.println("---------使用迭代器方式遍历---------");Iterator iterator = collection.iterator();while (iterator.hasNext()){Student s = (Student) iterator.next();System.out.println(s);}//(6)判断System.out.println("---------判断集合中元素---------");System.out.println(collection.contains(s2));}
}


http://www.mrgr.cn/news/43922.html

相关文章:

  • RabbitMQ入门1—queue参数之type
  • 国外电商系统开发-运维系统资产属性-命令执行功能
  • DINOv2: Learning Robust Visual Featureswithout Supervision
  • 代码随想录Day 62|Floyd 算法精讲、A \* 算法精讲 (A star算法),题目:97. 小明逛公园、127. 骑士的攻击
  • 【源码+文档】基于SpringBoot+Vue校园智慧迎新服务平台
  • 123456
  • Spring Data JPA中的锁机制
  • 速速收藏!这些2024年上映的AI电影与短剧,申请加入你的国庆假期宅家计划!
  • 前端公共资源CDN存储库大全
  • SpringBoot在线教育系统:架构设计与技术选型
  • 程序传入单片机的过程,以Avrdude为例分析
  • 固态硬盘数据丢失?别急,这4款恢复神器帮你找回“丢失的记忆”!
  • python:zip文件(加密了)之瞎猜密码
  • 吊打ChatGPT4o!大学生如何用上原版O1辅助论文写作(附论文教程)
  • 【Python】数据可视化之聚类图
  • 第十三章 Redis短信登录实战(基于Redis)
  • VB6.0 怎么让窗口固定没有放大只有缩小
  • 【数学二】一元函数微分学-导数的计算-复合函数的求导法则、反函数求导法则、隐函数求导法则
  • 面试官:MySQL 什么时候会出现死锁问题?为什么不推荐使用RR隔离级别?
  • msvcp140.dll丢失的解决方法,详细解读6种解决方法