欢迎访问我的技术群425783133
case 1:
public static void main(String[] args) {
List<Integer> ls = new ArrayList<Integer>();
(1);
(2);
(3);
(());
for (Integer in : ls) {
if (in == 3) {//in==2时,正常执行
(in);
}
}
(());
}
执行上面的代码时,程序会报错,只要是删除2以外的任何数,都会导致出错,
原因: 对于for(),java 虚拟机会将其翻译成Iterator迭代器,
java编译器中含有:hasNext()函数,而hasNext()函数中含有:size()函数,这意味着list数组的大小是动态生成的,
它是使用index!=size()来判定是否有下一个元素的,理论上只有最后元素才回返回false,其它元素都会返回true,一旦返回了true就会调用next,这样在调用next的过程中就会调用concurrentExceptions,在for()中,不容许调用remove()函数。
这也就解释了,删除倒数第二个数,不会导致报错,因为在判断倒数第二个数的时候,index!=size直接返回false,这样没有next
,也就不存在next的调用了。
解决办法:
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> ls = new ArrayList<Integer>();
(1);
(2);
(3);
int i = 0;
int len = ();
for (; i < len; i++) {
if ((i).equals(2)) {
((i));
i--;
len--;
}
}
(());
}
通过固定list的大小,然后每remove一个元素,紧接着使len元素减少,这样会不会出现这样的问题。