众所周知在使用Iterator对象迭代ArryList时候必须用迭代的添加和删除方法,不可直接使用ArrayList方法去改变集合的结构·~~~ 这样会有个cocurrent。。的异常抛出~~~基于此我写了如下代码import java.util.*;
class tt
{
public static void main(String[] args)
{ ArrayList<String> a=new ArrayList();
a.add("aaq");
a.add("ff");
Iterator<String> itr=a.iterator();
while(itr.hasNext()){
String h=(String)itr.next();
a.remove(h);
System.out.print(h);
}
}
}
运行完后并没有出现预期的异常抛出 反倒是只输出了一个aaq(删除的元素),这时候我就纳闷了ff咋就不能删除呢?若是在前面代码在加上a.add("cdwff");时候再运行就会发生错误,但不管怎样 两个元素的数组列表在删除一个之后hasNext()不应该为false呀 谁能给我解下疑惑·~~~~~~谢谢 还有我发现一点这个异常是在itr.next()位置发出 hasNext()不会抛出异常~~~~~
class tt
{
public static void main(String[] args)
{ ArrayList<String> a=new ArrayList();
a.add("aaq");
a.add("ff");
Iterator<String> itr=a.iterator();
while(itr.hasNext()){
String h=(String)itr.next();
a.remove(h);
System.out.print(h);
}
}
}
运行完后并没有出现预期的异常抛出 反倒是只输出了一个aaq(删除的元素),这时候我就纳闷了ff咋就不能删除呢?若是在前面代码在加上a.add("cdwff");时候再运行就会发生错误,但不管怎样 两个元素的数组列表在删除一个之后hasNext()不应该为false呀 谁能给我解下疑惑·~~~~~~谢谢 还有我发现一点这个异常是在itr.next()位置发出 hasNext()不会抛出异常~~~~~
while(itr.hasNext()){//
String h=(String)itr.next();
a.remove(h);//删除之后长度变为1了。
System.out.print(h);
}很明显不会执行第2次。也就不会删除“ff”了。你dubug就看的到了
boolean hasNext()Returns true if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing an exception.)
Returns:
true if the iterator has more elements.
--------------------------------------------------------------------------------
next
E next()Returns the next element in the iteration.
Returns:
the next element in the iteration.
Throws:
NoSuchElementException - iteration has no more elements.API告诉我们:hasNext方法只会返回true/false,不会抛出异常。
而next方法会抛出异常。
你想,当你把aaq删掉之后hasNext发现若调用next函数就会抛出异常,这样就返回false了,下面代码不会执行,
如果你加上a.add("cdwff");那样hasNext函数发现还有next,继续执行,这时next函数抛出异常:
at java.util.AbstractList$Itr.next(Unknown Source)
就是这样的~
class tt
{
public static void main(String[] args)
{ ArrayList<String> a=new ArrayList();
a.add("aaq");
a.add("ff");
a.add("ff");
Iterator<String> itr=a.iterator();
while(itr.hasNext()){
String h=(String)itr.next();
a.remove(h);
System.out.print(h);
}
}
}
可是为什么又会报错呢? 如果hasNext()判断next()返回的是个异常按你说的 应该就false了
那他怎么又继续运行抛出---------- javar ----------
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at tt.main(tt.java:12)输出完成 (耗时 0 秒) - 正常终止