以前也知道Arrays.asList 返回的List集合和现在java.util.List 集合不一样,但具体没看,今天在项目中用到并报错排查了一下就找到问题了,记录一下:
一、下面是Arrays类下的ArrayList 类和方法源码:
1、Arrays 调用方法
@SafeVarargs public static <T> List<T> asList(T... a) { return new ArrayList<>(a); }
/** * @serial include */ 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; } }
public void add(int index, E element) { throw new UnsupportedOperationException(); } public E remove(int index) { throw new UnsupportedOperationException(); } public E set(int index, E element) { throw new UnsupportedOperationException(); }
看到三个方法就知道了,通过Arrays 的到的List集合是一个只读集合,不能进行增、删、改 当然也就不能进行addAll(c); retainAll(c);removeAll(c); 这三个方法了
所以在使用的时候要注意,当时我看到一个博客中这样写着,说可以解决这个问题比如:
List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3));