纠结
- list的sublist(fromIndex,toIndex)方法取到的结果是 [fromIndex,toIndex)
代码示例
package com.qq
import java.util.ArrayList
import java.util.List
public class Rest {
public static void main(String[] args) {
List<String> list = new ArrayList<>()
list.add("zoo")
list.add("one")
list.add("two")
list.add("three")
list.add("four")
list.add("five")
System.err.println("list集合" + list)
List<String> lists = list.subList(0, 2)
System.err.println("lists的集合是:" + lists)
// list.add("dsf")
// System.err.println("lists的集合是:" + lists)
// for (String string : lists) {//注意集合应该是list不是lists,用list造成的结果是报错
// ConcurrentModificationException
// System.err.print(string + " ")
// if (string.equals("one")) {
// list.remove(string)
// }
// }
for (int i = 0
// System.err.println(string)
if (list.get(i).equals("one")) {
list.remove(i)
}
}
System.err.println(list)
}
}
输出结果
注释foreach的结果
list集合[zoo, one, two, three, four, five]
lists的集合是:[zoo, one]
[zoo, two, three, four, five]
注释for的结果
list集合[zoo, one, two, three, four, five]
lists的集合是:[zoo, one]
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$SubList.checkForComodification(Unknown Source)
at java.util.ArrayList$SubList.listIterator(Unknown Source)
at java.util.AbstractList.listIterator(Unknown Source)
at java.util.ArrayList$SubList.iterator(Unknown Source)
at java.util.AbstractCollection.toString(Unknown Source)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at com.qq.Rest.main(Rest.java:21)
小结
- 造成ConcurrentModificationException这个错误的原因可能是因为sublist的源码可能是用迭代器写的
- 用迭代器遍历数据时,不能对数据进行操作
参考