Java中Arrays.asList()方法詳解及實例
Arrays.asList() 是將數(shù)組作為列表。
問題來源于:
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ù),但是因為 int[] 本身就是一個類型,所以 a 變量作為參數(shù)傳遞時,編譯器認(rèn)為只傳了一個變量,這個變量的類型是 int 數(shù)組,所以 size 為 1,相當(dāng)于是 List 中數(shù)組的個數(shù)。基本類型是不能作為泛型的參數(shù),按道理應(yīng)該使用包裝類型,但這里缺沒有報錯,因為數(shù)組是可以泛型化的,所以轉(zhuǎn)換后在 list 中就有一個類型為 int 的數(shù)組。
/**
* 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ù)組的更改。
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。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
詳解Spring Cloud Netflix Zuul中的速率限制
這篇文章主要介紹了詳解Spring Cloud Netflix Zuul中的速率限制,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
JAVAEE Filter 過濾器設(shè)置是否緩存實例詳解
網(wǎng)頁中,每次的客戶端訪問服務(wù)器,有部分不用重復(fù)請求的,這樣可以減輕服務(wù)器的工作量。那么如何設(shè)置客戶端是否都緩存呢?接下來通過本文給大家介紹JAVAEE Filter 過濾器設(shè)置是否緩存的實例,感興趣的朋友一起學(xué)習(xí)吧2016-05-05
Spring Boot 集成 Mybatis Plus 自動填充字段的實例詳解
這篇文章主要介紹了Spring Boot 集成 Mybatis Plus 自動填充字段,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03
Spring?myBatis數(shù)據(jù)庫連接異常問題及解決
這篇文章主要介紹了Spring?myBatis數(shù)據(jù)庫連接異常問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06

