什么是迭代器?
考察点:JAVA 迭代器
参考回答:
Iterator 提供了统一遍历操作集合元素的统一接口, Collection 接口实现 Iterable 接口,每个集合都通过实现 Iterable 接口中 iterator()方法返回 Iterator 接口的实例, 然后对集合 的元素进行迭代操作. 有一点需要注意的是:在迭代元素的时候不能通过集合的方法删除元素, 否则会抛出 ConcurrentModificationException 异常. 但是可以通过 Iterator 接口中的 remove()方法进行删除.
使用Iterator的简单例子
public class TestIterator {
public static void main(String[] args) {
List list=new ArrayList();
Map map=new HashMap();
for ( int i= 0 ;i< 10 ;i++){
list.add(new String( “list” +i) );
map.put(i, new String( “map” +i));
} Iterator iterList= list.iterator();//List接口实现了Iterable接口
while (iterList.hasNext()){
String strList=(String)iterList.next();
System.out.println(strList.toString());
}
Iterator iterMap=map.entrySet().iterator();
while (iterMap.hasNext()){
Map.Entry strMap=(Map.Entry)iterMap.next();
System.out.println(strMap.getValue());
}}