基本类型数组不能直接转为list,因泛型不支持原始类型;arrays.aslist(int[])将整个数组视为单个元素,返回长度为1的list;正确方式是用stream.boxed().collect()或包装为integer[]后调用aslist。

基本类型数组不能直接转成 List,因为泛型不接受 int、long 这类原始类型——这是最常踩的坑。
为什么 Arrays.asList(int[]) 不行
它会把整个 int[] 当作一个元素,生成 List<int></int>,而不是你想要的 List<integer></integer>。这是因为 Arrays.asList() 的泛型参数是 T...,而 int[] 是一个对象,编译器不会自动拆箱或装箱。
- 错误现象:
System.out.println(Arrays.asList(new int[]{1, 2, 3}).size())输出1,不是3 - 正确等价写法:
Arrays.asList(new Integer[]{1, 2, 3})才返回长度为 3 的List<integer></integer> - 注意:
Arrays.asList()返回的是固定大小的列表,不支持add()、remove()
用 Stream 转换(Java 8+ 推荐)
这是目前最干净、语义最明确的方式,能自动完成装箱,并返回可变的 ArrayList。
int[] arr = {1, 2, 3};List<integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());</integer>-
long[]、double[]同理,分别用LongStream、DoubleStream,再调boxed() - 性能注意:小数组无感;大数组(百万级)时,
boxed()会产生大量临时Integer对象,GC 压力略增
第三方库如 Guava 或 Apache Commons(适合老项目)
如果项目已引入这些库,可以少写几行 Stream 流水线。
立即学习“Java免费学习笔记(深入)”;
- Guava:
Lists.newArrayList(Ints.asList(1, 2, 3))—— 注意Ints.asList()返回的是List<integer></integer>,但底层仍是原始数组封装,修改会影响原数组 - Apache Commons Lang:
ArrayUtils.toObject(intArray)先转成Integer[],再传给Arrays.asList() - 兼容性提醒:Guava 的
Ints.asList()在 JDK 17+ 某些模块配置下可能触发IllegalAccessError,慎用于模块化强的环境
真正容易被忽略的是:转换后是否需要修改列表。如果只是遍历或只读,用 Arrays.asList(包装后的数组) 最轻量;如果后续要 add 或 remove,必须套一层 new ArrayList(...) 或用 Stream.collect(),否则运行时报 UnsupportedOperationException。









