今天修改以前一个同事的代码,其中有一句是我新增的代码:
private static List<String> exceptionAPIs = new ArrayList<>();
//调用某些方法,处理数据
File file = new File(filePath);
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
while (!StringUtils.isEmpty(line)) {
list.add(line.trim());
line = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
结果却报了下面这个错误:
Caused by: java.lang.UnsupportedOperationException
at java.util.AbstractList.add (AbstractList.java:148)
at java.util.AbstractList.add (AbstractList.java:108)
从错误信息上看到,list的类型发生了变化,不在是java.util.ArrayList,而是java.util.AbstractList,找到这个类的add方法:
/**
* {@inheritDoc}
*
* <p>This implementation always throws an
* {@code UnsupportedOperationException}.
*
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
AbstractList是个抽象类,在执行我新写的代码之前,唯一的操作就是:
list = Arrays.asList(members.toArray(new String[]{}))
应该是这个方法的实现,改变了list的类型,找到这个方法:
/**
* Returns a fixed-size list backed by the specified array. (Changes to
* the returned list "write through" to the array.) This method acts
* as bridge between array-based and collection-based APIs, in
* combination with {@link Collection#toArray}. The returned list is
* serializable and implements {@link RandomAccess}.
*
* <p>This method also provides a convenient way to create a fixed-size
* list initialized to contain several elements:
* <pre>
* List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
* </pre>
*
* @param <T> the class of the objects in the array
* @param a the array by which the list will be backed
* @return a list view of the specified array
*/
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
返回的数据看起来是ArrayList,找到这个ArrayList,在Arrays中,是个内部类:
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
这个内部类实现上面的抽象类AbstractList,但是没有重写add方法,所以执行的还是抽象类中的add方法,而这个方法只会抛出异常 java.lang.UnsupportedOperationException,所以,解决这个问题只要把list的类型改回来就行了;
两种简单方式:
list = new ArrayList<>();
list = new ArrayList<>(list);