Arrays.asList() 是将数组作为列表。
问题来源于:
?
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,然而结果是1。
原因如下:
在 Arrays.asList 中,该方法接受一个变长参数,一般可看做数组参数,但是因为 int[] 本身就是一个类型,所以 a 变量作为参数传递时,编译器认为只传了一个变量,这个变量的类型是 int 数组,所以 size 为 1,相当于是 List 中数组的个数。基本类型是不能作为泛型的参数,按道理应该使用包装类型,但这里缺没有报错,因为数组是可以泛型化的,所以转换后在 list 中就有一个类型为 int 的数组。
?
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);
}
|
返回一个受指定数组支持的固定大小的列表。(对返回列表的更改会“直写”到数组。)此方法同 Collection.toArray 一起,充当了基于数组的 API 与基于 collection 的 API 之间的桥梁。返回的列表是可序列化的。
所以,如果是创建多个列表,在传参数时候,最好使用 Arrays.copyOf(a) 方法,不然,对列表的更改就相当于对数组的更改。
?
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[] 数组没有赋值的话,默认是 null,而不是像 int[] 数组默认是 0。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://www.123si.org/java/274.html
相关文章
猜你喜欢
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
CentOS Linux系统搭建Android开发环境详细介绍
2025-05-27 16 -
2025-05-25 53
-
2025-06-04 18
-
2025-05-27 46
-
2025-06-04 56
热门评论