Collection体系
collection的使用
添加和删除元素:
public static void main(String[] args) {
//创建集合
Collection collection = new ArrayList();
//添加元素
collection.add("西瓜");
collection.add("苹果");
collection.add("榴莲");
System.out.println("元素个数:"+collection.size());
System.out.println(collection);
//删除元素
collection.remove("榴莲");
System.out.println("删除之后个数:"+collection.size());
结果:
元素个数:3
[西瓜, 苹果, 榴莲]
删除之后个数:2
clear方法可以全部删除
但需要注意的是,把对象存入集合,实际上是将对象的地址加入到集合中,从集合删除对象,对象依然存在,并未消失。可以理解为把快捷方式删了但软件还在
遍历:
重点:迭代器
- hasNext() 有没有下一个元素
- next() 获取下一个元素
- remove() 删除当前元素
//遍历
//1.使用增强for
for (Object o :
collection) {
System.out.println(o);
}
//2,使用迭代器,迭代器是专门遍历集合的一种方式
Iterator it = collection.iterator();
while (it.hasNext()){
String s = (String) it.next();
System.out.println(s);//已经知道存的是字符串,可以强转。不知道的话就是Object类型
collection.remove(s);//报异常
}
注意:使用迭代器过程中不能再调用该collection的其他方法,否则会产生并发修改异常,比如上段代码中调用了remove就会报错
而应该改为:
it.remove();
这样来删除正在遍历的当前元素
判断:
//判断
System.out.println("有没有特定元素:"+collection.contains("西瓜"));
使用collection保存学生信息
//使用collection保存学生信息
public static void main(String[] args) {
Collection collection = new ArrayList<>();
Student s1 = new Student("张三",18);
Student s2 = new Student("张屋脊",38);
Student s3 = new Student("李四",32);
//1.添加数据
collection.add(s1);
collection.add(s2);
collection.add(s3);
System.out.println("元素个数:"+collection.size());
System.out.println(collection.toString());
//遍历1:增强for
for (Object o:
collection) {
Student s = (Student)o ;
System.out.println(s.toString());
}
//遍历2:迭代器
Iterator it = collection.iterator();
while (it.hasNext()){
Student student =(Student) it.next();
System.out.println(student.toString());
}
}