gpt4 book ai didi

Java subList ConcurrentModificationException();

转载 作者:行者123 更新时间:2023-11-30 09:04:36 26 4
gpt4 key购买 nike

我已经定义了 ArrayList:

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

我只想处理它的特定部分,所以我创建了子列表:

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

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

numbers.remove(p + 1);

在我尝试再次使用 subList 之前它可以正常工作:

numbersh.remove(0);

我收到/from 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);这超出了 subList 范围,应该导致

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

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

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

我有点迷茫了。有什么想法吗?

最佳答案

您忘记了 subList() 确实返回新列表,而只是原始列表的一部分。

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 的深拷贝。

关于Java subList ConcurrentModificationException();,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25159552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com