zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java数组转ArrayList的注意事项详解编程语言

JAVA数组编程语言 详解 注意事项 ArrayList
2023-06-13 09:11:51 时间

今天做一道题目时,遇到了一个问题——将一个int[]数组转化成List Integer 类型,好像是一个挺常见的场景。于是立刻写下:

ArrayList Integer list = new ArrayList (Arrays.asList(array)); 

结果就报错了:

Line 22: error: incompatible types: Integer[] cannot be converted to int[] 

 int[] temp = new Integer[size]; 

Line 35: error: incompatible types: inference variable T has incompatible bounds 

 List Integer list = Arrays.asList(temp); 

 equality constraints: Integer 

 lower bounds: int[] 

 where T is a type-variable: 

 T extends Object declared in method T asList(T...) 

2 errors 

为什么报格式不匹配呢?

因为Arrays.asList()是泛型方法,传入的对象必须是对象数组。如果传入的是基本类型的数组,那么此时得到的list只有一个元素,那就是这个数组对象int[]本身。

解决方法

将基本类型数组转换成包装类数组,这里将int[]换成Integer[]即可。

19350.html

cjavaxml