Arrays.asList() 是將數組作為列表。
問題來源于:
1
2
3
4
5
6
7
|
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 的數組。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
/** * 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<String> 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) 方法,不然,對列表的更改就相當于對數組的更改。
1
2
3
4
5
6
7
|
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。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://www.123si.org/java/274.html