1.問題描述
今天在做算法的時候用到了list.add()方法,結果報了UnsupportedOperationException 錯誤
List<List<String>> res = new ArrayList<>();
//中間代碼省略
res.get(key).add(str);
2.分析
去網上查了之後基本上都是由于使用了Arrays.asList()方法導緻的報錯,而我并沒有使用這個方法。經過調試之後發現,問題出在get方法傳回的list。由于我傳入的對象是List,而list.get()方法傳回的集合預設是Collections下的内部靜态類SingletonList。
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIyVGduV2YfNWawNyZuBnLxITO1UDOzQTMzITOwAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
private static class SingletonList<E> extends AbstractList<E> implements RandomAccess, Serializable {
private static final long serialVersionUID = 3093736618740652951L;
private final E element;
SingletonList(E obj) {
this.element = obj;
}
public Iterator<E> iterator() {
return Collections.singletonIterator(this.element);
}
public int size() {
return 1;
}
public boolean contains(Object obj) {
return Collections.eq(obj, this.element);
}
public E get(int index) {
if (index != 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: 1");
} else {
return this.element;
}
}
public void forEach(Consumer<? super E> action) {
action.accept(this.element);
}
public boolean removeIf(Predicate<? super E> filter) {
throw new UnsupportedOperationException();
}
public void replaceAll(UnaryOperator<E> operator) {
throw new UnsupportedOperationException();
}
public void sort(Comparator<? super E> c) {
}
public Spliterator<E> spliterator() {
return Collections.singletonSpliterator(this.element);
}
public int hashCode() {
return 31 + Objects.hashCode(this.element);
}
}
可以發現,此類中并沒有重寫父類AbstractList的add方法,是以會調用父類AbstractList的add方法。再看看AbstractList的add方法。
public boolean add(E e) {
this.add(this.size(), e);
return true;
}
讓我們ctrl繼續放下看
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
可以看到父類也并沒有實作add操作,而是直接抛出UnsupportedOperationException異常,這就是異常出現的原因了。
3.解決方法:
将List替換為具體實作了add方法的子類,然後就可以愉快的進行添加操作了
List<ArrayList<String>> res = new ArrayList<>();
res.get(temp).add(str);