Arrays.asList() 是將數(shù)組作為列表。
問題來源于:
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,然而結(jié)果是1。
原因如下:
在 Arrays.asList 中,該方法接受一個變長參數(shù),一般可看做數(shù)組參數(shù),但是因?yàn)?int[] 本身就是一個類型,所以 a 變量作為參數(shù)傳遞時,編譯器認(rèn)為只傳了一個變量,這個變量的類型是 int 數(shù)組,所以 size 為 1,相當(dāng)于是 List 中數(shù)組的個數(shù)。基本類型是不能作為泛型的參數(shù),按道理應(yīng)該使用包裝類型,但這里缺沒有報錯,因?yàn)閿?shù)組是可以泛型化的,所以轉(zhuǎn)換后在 list 中就有一個類型為 int 的數(shù)組。
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); } |
返回一個受指定數(shù)組支持的固定大小的列表。(對返回列表的更改會“直寫”到數(shù)組。)此方法同 Collection.toArray 一起,充當(dāng)了基于數(shù)組的 API 與基于 collection 的 API 之間的橋梁。返回的列表是可序列化的。
所以,如果是創(chuàng)建多個列表,在傳參數(shù)時候,最好使用 Arrays.copyOf(a) 方法,不然,對列表的更改就相當(dāng)于對數(shù)組的更改。
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[] 數(shù)組沒有賦值的話,默認(rèn)是 null,而不是像 int[] 數(shù)組默認(rèn)是 0。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://www.123si.org/java/274.html