Arrays.asList( ) 返回一個特殊的“ArrayList”


一個Arrays.asList()基本的用法:

String[] str = new String[]{"1","2","3"};
ArrayList al = new ArrayList(Arrays.asList(str));//將數組元素添加到集合的一種快捷方式

有時候這樣使用就有可能出現問題:

String[] str = new String[]{"1","2","3"};
List aslist = Arrays.asList(str);

aslist是List類型的對象,但是調用List接口的方法的時候會出錯就像這樣:

aslsit.add("4");
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(Unknown Source)
	at java.util.AbstractList.add(Unknown Source)
	at test.LinkedListTest.main(LinkedListTest.java:13)

出現這個錯誤的原因是沒有定義add()方法的具體實現,這些異常都在AbstractList拋出,看一下Arrays源碼:

@SafeVarargs
public static <T> List<T> asList(T... a) {
     return new ArrayList<>(a);
}

沒有問題啊,返回的是一個ArrayList,但是這個ArrayList不是ArrayList.class而是Arrays$ArrayList這樣一個內部類

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;
        }
    }

這個內部類中並沒有實現list的一些方法,所以調用add(),remove()這些方法都會出現錯誤。

這個內部類中有一個泛型的數組private final E[] a,所以Arrays.asList返回的集合中的數組其實是有具體的類型的,而不是Object[]。

相當於List<String> list = new Arrays$ArrayList<String>();

但是有類型的數組在轉換過程中就會出現某些問題,有個Bug就是這樣引起的。具體見 《c.toArray might not return Object[]》。  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM