//coll是集合对象
Iterator iter = coll.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
System.out.println(iter.next().getClass());
}
Exception in thread “main” java.util.NoSuchElementException
异常原因,迭代器指向空时抛异常。
Iterator iter = coll.iterator();
while (iter.hasNext()) {
iter.next();
coll.add("a");
}
Exception in thread “main” java.util.ConcurrentModificationException
并发修改异常;
就是同时修改异常,迭代器操作集合时,不允许集合自己 ”增“,”删“。
while (iter.hasNext()) {
iter.remove();
System.out.println(iter.next());
}
//或者
while (iter.hasNext()) {
System.out.println(iter.next());
iter.remove();
iter.remove();
}
Exception in thread “main” java.lang.IllegalStateException
值得注意的是迭代器使用时,一个循环里最好只写一个迭代器的操作,否则容易抛异常
while (iter.hasNext()) {
System.out.println(iter.next());
iter.remove();
}//这个是不会抛异常的