使用Iterator 接口遍历集合元素
- Iterator对象称为迭代器(设计模式的一一种),主要用于遍历Collection集合中的元素。
- GOF给迭代器模式的定义为:提供–种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。
- 迭代器模式,就是为容器而生。类似于“公交车上的售票员”、“火车上的乘务员”、“空姐” 。
- Collection接口继承了java.lang.lterable接口, 该接口有一个iteratior()方法, 那么所
有实现了Collection接口的集合类都有一个iterator()方法,用以返回一个实现了Iterator接口的对象。 - Iterator仅用于遍历集合,Iterator本身并不提供承装对象的能力。如果需要创建
Iterator对象,则必须有一个被迭代的集合。 - 集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合
的第一个元素之前。
方法和使用
1. hasNext()和next()
Iterator iterator = hashSet1.iterator();
//hasNext() : 判断当前指针的下一个位置是否有元素,指针不会下移
while (iterator.hasNext()){
//next():指针下移并返回下移后指针位置的元素
System.out.println(iterator.next());
}
- Iterator不是容器,就是用来遍历集合的,不装任何元素,不会产生新的集合
2. remove()
Collection collection = new ArrayList();
collection.add(123);
collection.add("abc");
collection.add(new Date());
collection.add(false);
System.out.println(collection);
//移除abc
Iterator iterator = collection.iterator();
while (iterator.hasNext()){
Object object = iterator.next();
if ("abc".equals(object))
iterator.remove();
}
//需要重新获取一个iterator,上一个iterator的指针已经指向末尾了
iterator = collection.iterator();//让iterator的指针重新指向collection的第一个元素
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
注意:
- Iterator可以删除集合的元素,但是是遍历过程中通过迭代器对象的remove方法,不是集合对象的remove方法。
- 如果还未调用next()或在上一次调用next 方法之后已经调用了remove 方法,再调用remove都会报llgalStateException。(在调用next之前,不要调用remove)