什么是集合?
对象的容器,实现了对对象的常用操作,类似于数组功能。
1、集合和数组的区别
2、Collection体系集合
3、Collection接口的方法
迭代器(Iterator)迭代器的三种方法:
hasnext() :有没有下一个元素
next();获取下一个元素
remove();删除当前元素
正确用法
//2.迭代器(专门遍历集合的接口)
Iterator iterator = collection.iterator();
while (iterator.hasNext()){
Object object = iterator.next();
System.out.println(object);
}
错误用法
//错误用法1 每一次都会创建一个Iterator对象,每次输出的都是第一个元素,会发生死循环
while (collection.iterator().hasNext()){
System.out.println(collection.iterator().next());
}
//错误用法2 会进行跳跃式输出,还会出现NoSuchElementsException
while (iterator.next()!=null){
System.out.println(iterator.next());
}
public class TestCollection {
public static void main(String[] args) {
//创建集合
Collection collection = new ArrayList();
//添加元素
collection.add("苹果");
collection.add("西瓜");
collection.add("榴莲");
System.out.println(collection);
//删除元素
//collection.remove("西瓜");
System.out.println(collection);
//遍历
//1.增强for
for (Object x:collection) {
System.out.println(x);
}
//2.迭代器(专门遍历集合的接口)
Iterator iterator = collection.iterator();
while (iterator.hasNext()){
Object object = iterator.next();
System.out.println(object);
//collection.remove(object); //不能使用collection的remove(),会造成并发修改异常
//iterator.remove(); //可以使用迭代器删除当前元素
}
//判断
System.out.println(collection.contains("苹果"));
System.out.println(collection.isEmpty());
}
}
public class TestCollection2 {
public static void main(String[] args) {
Collection collection = new ArrayList();
Student s1 = new Student("aaa", 18);
Student s2 = new Student("bbb", 18);
Student s3 = new Student("ccc", 18);
//添加
collection.add(s1);
collection.add(s2);
collection.add(s3);
collection.add(s3);
System.out.println(collection.toString());
//删除
collection.remove(s1);
System.out.println(collection.toString());
//清空
// collection.clear();
// System.out.println(collection.toString());
// System.out.println(s1.toString()); //还有
//增强for
for (Object object :
collection) {
System.out.println(object);
}
//Iterator迭代器
Iterator iterator = collection.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println(collection.contains(s2));
System.out.println(collection.isEmpty());
}
}
参考