Java subList ConcurrentModificationException();

时间:2014-08-06 11:44:01

标签: java android arraylist sublist

我已经定义了ArrayList:

ArrayList<String> numbers = new ArrayList<String>();

我只是想在它的特定部分工作,所以我创建了subList:

List<String> numbersh = numbers.subList(o, p + 1);

我理解一个基本概念,它对我有用,直到我意识到需要自己使用ArrayList:

numbers.remove(p + 1);

正常工作,直到我再次尝试使用subList:

numbersh.remove(0);

我收到/来自AbstractList.class /:

throw new ConcurrentModificationException();

为了更好地理解,请按照ArrayList / numbers /:

进行设想

[1,2,3,4,5,6,7,8] /数字/

及其 List<String> numbersh = numbersh.subList(3, 5);由[4,5,6]

组成

我正在做的是numbers.remove(6);,这超出了子列表范围,应该导致

[1,2,3,4,5,6,8] /数字/

然后我尝试numbersh.remove(0)导致:

[1,2,3,5,6,8] /数字/

我很幸运。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

你忘了subList()返回新的List,而只是原始List的一部分。

public List<E> subList(int fromIndex, int toIndex) {
    subListRangeCheck(fromIndex, toIndex, size);
    return new SubList(this, 0, fromIndex, toIndex);
}

SubList(AbstractList<E> parent,
        int offset, int fromIndex, int toIndex) {
    this.parent = parent;
    this.parentOffset = fromIndex;
    this.offset = offset + fromIndex;
    this.size = toIndex - fromIndex;
    this.modCount = ArrayList.this.modCount;
}

如果您需要单独修改和访问List和subList,则需要创建原始List的深层副本。

相关问题