Java数组转ArrayList的注意事项

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值