Arrays.asList的用法

JDK1.8的官方文档中 是这样写的

@SafeVarargs
public static List asList(T… a)
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 Collection.toArray(). The returned list is serializable and implements RandomAccess.
This method also provides a convenient way to create a fixed-size list initialized to contain several elements:
                List stooges = Arrays.asList(“Larry”, “Moe”, “Curly”);
Type Parameters:
T - the class of the objects in the array
Parameters:
a - the array by which the list will be backed
Returns:
a list view of the specified array

翻译一下:

@SafeVarargs
public static List asList(T… a)
返回由指定数组支持的固定大小的列表。(更改为返回列表,将其“写入”到数组。)与Collection.toArray()结合使用,此方法充当基于数组的API和基于集合的API之间的桥梁。 返回的列表是可序列化的,并实现RandomAccess。
此方法还提供了一种方便的方法来创建固定大小的列表,该列表初始化为包含多个元素:
List stooges = Arrays.asList(“ Larry”,“ Moe”,“ Curly”);
类型参数:
T-数组中对象的类
参数:
a-将支持列表的数组
返回值:
指定数组的列表视图

使用工具类Arrays.asList()把数组转换成集合时,不能使用其修改集合相关的方法,它的add/remove/clear方法会抛出UnsupportOperationException异常
说明:

asList的返回对象是一个Arrays内部类,并没有实现集合的修改方法。Arrays.asList体现的是适配器模式,只是转换接口,后台的数据仍是数组。

String[] str = new String[]{"1","2"};
List list = Arrays.asList(str);

第一种情况:list.add(“x”);//运行时异常
第二种情况:str[0] = “unv”;//那么list.get(0)也随着修改。

此类包含用来操作数组(比如排序和搜索)的各种方法。此类还包含一个允许将数组作为列表来查看的静态工厂。 除非特别注明,否则如果指定数组引用为 null,则此类中的方法都会抛出 NullPointerException。一段有意思的代码如下:

public static void main(String[] args) {
	int[] array = {2, 3, 5, 8, 9};
	List list = Arrays.asList(array);
	System.out.println("列表中的元素数量是:" + list.size());
}

       这里输出的数量是1,在Arrays.asList中,该方法接受一个变长参数,一般可看做数组参数,但是因为int[] 本身就是一个类型,所以array变量作为参数传递时,编译器认为只传了一个变量,这个变量的类型是int数组,所以size为1。基本类型是不能作为泛型的参数,按道理应该使用包装类型,但这里却没有报错,因为数组是可以泛型化的,所以转换后在list中就有一个类型为int的数组

int[] array = {2, 3, 5, 8, 9};
List list = Arrays.asList(array);
System.out.println("元素类型:" + list.get(0).getClass());
System.out.println("前后是否相等:" + array.equals(list.get(0)));

结果:
元素类型:class [I
前后是否相等:true

因为JVM不可能输出array类型,array类型属于java.lang.reflect包,通过反射访问数组的这个类,编译时候生成的。所以要改为:

public static void main(String[] args) {
	Integer[] array = {2, 3, 5, 8, 9};
	List list = Arrays.asList(array);
	System.out.println("列表中的元素数量是:" + list.size());
}

输出结果:
列表中的元素数量是:5
说明编译器对Integer[] 处理不一样。Integer是可变长参数。传入过程中asList()方法实际是将Integer数组里的元素进行存储。

参考:
https://www.cnblogs.com/hoobey/p/6661294.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值