For some reason, I get an UnsupportedOpeationException with the following code. Looking at it in the debugger, it looks like an object that I call remove() on - this is a list.
// 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; }
An 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)
Why is this happening?
source share