Java中Arrays.asList()方法详解及实例
Arrays.asList()是将数组作为列表。
问题来源于:
publicclassTest{
publicstaticvoidmain(String[]args){
int[]a={1,2,3,4};
Listlist=Arrays.asList(a);
System.out.println(list.size());//1
}
}
期望的输出是list里面也有4个元素,也就是size为4,然而结果是1。
原因如下:
在Arrays.asList中,该方法接受一个变长参数,一般可看做数组参数,但是因为int[]本身就是一个类型,所以a变量作为参数传递时,编译器认为只传了一个变量,这个变量的类型是int数组,所以size为1,相当于是List中数组的个数。基本类型是不能作为泛型的参数,按道理应该使用包装类型,但这里缺没有报错,因为数组是可以泛型化的,所以转换后在list中就有一个类型为int的数组。
/**
*Returnsafixed-sizelistbackedbythespecifiedarray.(Changesto
*thereturnedlist"writethrough"tothearray.)Thismethodacts
*asbridgebetweenarray-basedandcollection-basedAPIs,in
*combinationwith{@linkCollection#toArray}.Thereturnedlistis
*serializableandimplements{@linkRandomAccess}.
*
*Thismethodalsoprovidesaconvenientwaytocreateafixed-size
*listinitializedtocontainseveralelements:
*
*List<String>stooges=Arrays.asList("Larry","Moe","Curly");
*
*
*@paramathearraybywhichthelistwillbebacked
*@returnalistviewofthespecifiedarray
*/
@SafeVarargs
publicstaticListasList(T...a){
returnnewArrayList<>(a);
}
返回一个受指定数组支持的固定大小的列表。(对返回列表的更改会“直写”到数组。)此方法同Collection.toArray一起,充当了基于数组的API与基于collection的API之间的桥梁。返回的列表是可序列化的。
所以,如果是创建多个列表,在传参数时候,最好使用Arrays.copyOf(a)方法,不然,对列表的更改就相当于对数组的更改。
publicclassTest{
publicstaticvoidmain(String[]args){
Integer[]a={1,2,3,4};
Listlist=Arrays.asList(a);
System.out.println(list.size());//4
}
}
最后提醒,如果Integer[]数组没有赋值的话,默认是null,而不是像int[]数组默认是0。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!