今天做一道题目时,遇到了一个问题——将一个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[]即可。

本文探讨了在Java中将基本类型数组转换为ArrayList时遇到的问题。当使用泛型方法转换基本类型数组,如int[],会得到一个只包含数组对象的ArrayList,而不是元素。解决方案是先将基本类型数组转换为对应的包装类数组,例如Integer[]。
2106

被折叠的 条评论
为什么被折叠?



