先来一段代码:
ArrayList a = new ArrayList();
a.add(new Integer(3));
Iterator it = a.iterator();
a.add(new String("hellow"));
while(it.hasNext())
{
System.out.println(it.next());
}
咋一看,这段代码貌似没有问题。可是运行之后却会报异常。
原因在哪里呢?
事实上,在编程过程中,容易出现先指定迭代器iterator,然后对链表增加节点,这样做是错误的。
原因是:由于在进行遍历集合时不能改变集合的长度,如果采用集合自带的API比如add、remove等方法对集合进行相关操作时候就会抛出异常。