java——Arrays.asList()方法


Arrays.asList() 是將數組作為列表

問題來源於:

public class Test {
    public static void main(String[] args) {
        int[] a = {1,2,3,4};
        List list = Arrays.asList(a);
        System.out.println(list.size());  //1
    }

}

期望的輸出是 list里面也有4個元素,也就是size為4,然而結果是1.

原因如下:

在Arrays.asList中,該方法接受一個變長參數,一般可看做數組參數,但是因為int[] 本身就是一個類型,所以a變量作為參數傳遞時,編譯器認為只傳了一個變量,這個變量的類型是int數組,所以size為1,相當於是List中數組的個數。基本類型是不能作為泛型的參數,按道理應該使用包裝類型,但這里缺沒有報錯,因為數組是可以泛型化的,所以轉換后在list中就有一個類型為int的數組

/**
     * 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&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");
     * </pre>
     *
     * @param a the array by which the list will be backed
     * @return a list view of the specified array
     */
    @SafeVarargs
    public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

返回一個受指定數組支持的固定大小的列表。(對返回列表的更改會“直寫”到數組。)此方法同 Collection.toArray 一起,充當了基於數組的 API 與基於 collection 的 API 之間的橋梁。返回的列表是可序列化的.

所以,如果是創建多個列表,在傳參數時候,最好使用Arrays.copyOf(a)方法,不然,對列表的更改就相當於對數組的更改。

public class Test {
    public static void main(String[] args) {
        Integer[] a = {1,2,3,4};
        List list = Arrays.asList(a);
        System.out.println(list.size());  //4
    }

}

最后提醒,如果Integer[]數組沒有賦值的話,默認是null,而不是像int[]數組默認是0。

 


免責聲明!

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



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