本篇文章給大家分享的是有關(guān)Arrays.asList()如何在Java項目中使用,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

我們提供的服務有:成都網(wǎng)站制作、網(wǎng)站建設、外貿(mào)網(wǎng)站建設、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認證、義縣ssl等。為成百上千家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務,是有科學管理、有技術(shù)的義縣網(wǎng)站制作公司
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ù)傳遞時,編譯器認為只傳了一個變量,這個變量的類型是 int 數(shù)組,所以 size 為 1,相當于是 List 中數(shù)組的個數(shù)。基本類型是不能作為泛型的參數(shù),按道理應該使用包裝類型,但這里缺沒有報錯,因為數(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 一起,充當了基于數(shù)組的 API 與基于 collection 的 API 之間的橋梁。返回的列表是可序列化的。
所以,如果是創(chuàng)建多個列表,在傳參數(shù)時候,最好使用 Arrays.copyOf(a) 方法,不然,對列表的更改就相當于對數(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ù)組沒有賦值的話,默認是 null,而不是像 int[] 數(shù)組默認是 0。
以上就是Arrays.asList()如何在Java項目中使用,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學到更多知識。更多詳情敬請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
新聞標題:Arrays.asList()如何在Java項目中使用
標題URL:http://chinadenli.net/article38/pgjssp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、網(wǎng)站制作、、定制開發(fā)、面包屑導航、自適應網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)