由于某种原因,我得到了一个带有以下代码的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):
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 创建的。

09-10 06:27
查看更多