Arrays.asList()是个坑


在java语言中,把数组转换成List集合,有个很方便的方法就是

List list = Arrays.asList("a","b","c");

如果你之前没有对返回来 list 进行操作(addremove),那么就完美避开了这个

list.add("d"); // list.remove(1);
System.out.println(list);
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)

疑问! 为什么会抛异常?

源码分析 Arrays.class

public class Arrays {
        
    public static  List asList(T... a) {
              return new ArrayList<>(a);
    }
   /**
    * @serial include
    */
    private static class ArrayList extends AbstractList
           implements RandomAccess, java.io.Serializable
   {
        private final E[] a;
        ArrayList(E[] array) {
            a = Objects.requireNonNull(array);
        }
        ....       
    }
   ...
}

看源码才知道 Arrays.asList() 返回是 Arrays 中的一个私有内部类 java.util.Arrays.ArrayList 而并非我们用的 java.util.ArrayList

private static class ArrayList extends AbstractList implements RandomAccess, java.io.Serializable {
        private static final long serialVersionUID = -2764017481108945198L;
        private final E[] a;

        ArrayList(E[] array) {
            a = Objects.requireNonNull(array);
        }

        @Override
        public int size() {
            return a.length;
        }

        @Override
        public Object[] toArray() {
            return a.clone();
        }

        @Override
        @SuppressWarnings("unchecked")
        public  T[] toArray(T[] a) {
            int size = size();
            if (a.length < size)
                return Arrays.copyOf(this.a, size, (Class) a.getClass());
            System.arraycopy(this.a, 0, a, 0, size);
            if (a.length > size)
                a[size] = null;
            return a;
        }

        @Override
        public E get(int index) {
            return a[index];
        }

        @Override
        public E set(int index, E element) {
            E oldValue = a[index];
            a[index] = element;
            return oldValue;
        }

        @Override
        public int indexOf(Object o) {
            E[] a = this.a;
            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;
        }

        @Override
        public boolean contains(Object o) {
            return indexOf(o) != -1;
        }

        @Override
        public Spliterator spliterator() {
            return Spliterators.spliterator(a, Spliterator.ORDERED);
        }

        @Override
        public void forEach(Consumer action) {
            Objects.requireNonNull(action);
            for (E e : a) {
                action.accept(e);
            }
        }

        @Override
        public void replaceAll(UnaryOperator operator) {
            Objects.requireNonNull(operator);
            E[] a = this.a;
            for (int i = 0; i < a.length; i++) {
                a[i] = operator.apply(a[i]);
            }
        }

        @Override
        public void sort(Comparator c) {
            Arrays.sort(a, c);
        }
    }

接着这个内部类java.util.Arrays.ArrayList 继承了 AbstractList , 重写了一堆方法,但并没有重写我们用的 add 和 remove 方法。

public abstract class AbstractList extends AbstractCollection implements List {
        public boolean add(E e) {
            add(size(), e);
            return true;
        }

        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.asList() 返回是 Arrays 中的一个私有内部类 java.util.Arrays.ArrayList 而并非我们用的 java.util.ArrayList

java.util.Arrays.ArrayList 内部类继承了 AbstractList并且没有重写 add() 、remove() 方法。

java.util.AbstractList add() 、remove() 、set() 就负责抛出一个 UnsupportedOperationException() 异常

解决办法

再次 list = new ArrayList<>(list);

List list = Arrays.asList("a", "b", "c");
// java.util.ArrayList
list  = new ArrayList<>(list);
list.add("d");
System.out.println(list);
[a, b, c, d]

你可能感兴趣的:(Arrays.asList()是个坑)