使用Arrays.asList()去处理一个数组的时候,报错
java.lang.UnsupportedOperationException
查看源码发现如下:
在Arrays.java, asList()方法是构建了一个ArrayList,但是这个是属于Arrays.ArrayList
这个和ArrayList是不同的东西,看下ArrayList
也就是说Array.ArrayList并没有实现诸如clear()等方法,固有错误报出
java.lang.UnsupportedOperationException
String[] arrayStr = new String[4];
arrayStr[0] = "0";
arrayStr[1] = "1";
arrayStr[2] = "2";
arrayStr[3] = "3";
List<String> list = Arrays.asList(arrayStr);
list.clear();
查看源码发现如下:
在Arrays.java, asList()方法是构建了一个ArrayList,但是这个是属于Arrays.ArrayList
@SafeVarargs
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private final E[] a;
ArrayList(E[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
public int size() {
return a.length;
}
public Object[] toArray() {
return a.clone();
}
public <T> T[] toArray(T[] a) {
int size = size();
if (a.length < size)
return Arrays.copyOf(this.a, size,
(Class<? extends T[]>) a.getClass());
System.arraycopy(this.a, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
public E get(int index) {
return a[index];
}
public E set(int index, E element) {
E oldValue = a[index];
a[index] = element;
return oldValue;
}
public int indexOf(Object o) {
if (o==null) {
for (int i=0; i<a.length; i++)
if (a[i]==null)
return i;
} else {
for (int i=0; i<a.length; i++)
if (o.equals(a[i]))
return i;
}
return -1;
}
public boolean contains(Object o) {
return indexOf(o) != -1;
}
}
这个和ArrayList是不同的东西,看下ArrayList
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
也就是说Array.ArrayList并没有实现诸如clear()等方法,固有错误报出