gpt4 book ai didi

Java:为什么在 List 上调用 `remove()` 会抛出 UnsupportedOperation 异常?

转载 作者:搜寻专家 更新时间:2023-11-01 01:00:12 26 4
gpt4 key购买 nike

出于某种原因,我收到了带有以下代码的 UnsupportedOpeationException。在调试器中检查它,看起来我调用 remove() 的对象是一个列表。

// to optimize, remove totalSize. After taking an item from lowest, if lowest is empty, remove it from `lists`
// lists are sorted to begin with
public static <T extends Comparable<? super T>> List<T> merge(Set<List<T>> lists) {
List<T> result = new ArrayList<T>();
HashMap<List<T>, Integer> location = new HashMap<List<T>, Integer>();

int totalSize = 0; // every element in the set
for (List<T> l : lists) {
location.put(l, 0);
totalSize += l.size();
}

boolean first;
List<T> lowest = lists.iterator().next(); // the list with the lowest item to add
int index;

while (result.size() < totalSize) { // while we still have something to add
first = true;

for (List<T> l : lists) {
if (! l.isEmpty()) {
if (first) {
lowest = l;
}
else if (l.get(location.get(l)).compareTo(lowest.get(location.get(lowest))) <= 0) {
lowest = l;
}
}
}
index = location.get(lowest);
result.add(lowest.get(index));
lowest.remove(index); //problem here
}
return result;
}

异常:

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(Unknown Source)
at interview.questions.MergeLists.merge(MergeLists.java:72)
at interview.questions.MergeLists.main(MergeLists.java:32)

为什么会这样?

最佳答案

很可能您收到的 List 的底层实现是固定长度的,例如 Arrays#asList 创建的.

关于Java:为什么在 List 上调用 `remove()` 会抛出 UnsupportedOperation 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1773352/

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