You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将存储整数的ArrayList转为普通整型数组?转换失败求助

将ArrayList转换为int[]的几种解决方案

嘿,我来帮你搞定这个转换问题!你说你的ArrayList<Integer> Temp能正常读取数据,但转普通int数组失败,大概率是用错了转换方式,我给你整理几种靠谱的方法,还有要避开的坑:

方法一:手动循环遍历(最通用,无版本依赖)

这是最基础也最不容易出错的方式,适合所有Java版本,能清晰看到转换过程:

// 假设你的ArrayList已经初始化并填充了数据
ArrayList<Integer> temp = new ArrayList<>();
// 创建对应长度的int数组
int[] intArray = new int[temp.size()];
// 遍历赋值,Integer会自动拆箱为int
for (int i = 0; i < temp.size(); i++) {
    intArray[i] = temp.get(i);
}

如果你的列表里可能存在null值(虽然你说能正常读取数据,但还是提一下),可以加个判空避免空指针:

intArray[i] = temp.get(i) != null ? temp.get(i) : 0; // 或者你想要的默认值

方法二:Java 8+ Stream API(简洁高效)

如果你的项目用的是Java 8或更高版本,用Stream一行代码就能搞定,非常优雅:

int[] intArray = temp.stream()
                     .mapToInt(Integer::intValue) // 把Integer转成int
                     .toArray(); // 生成int数组

甚至可以更短,利用自动拆箱特性:

int[] intArray = temp.stream().mapToInt(i -> i).toArray();

方法三:借助Apache Commons Lang工具类(已有依赖时用)

如果你的项目已经引入了Apache Commons Lang库,用工具类会更省心:

import org.apache.commons.lang3.ArrayUtils;

// 先转成Integer数组,再转成int数组
int[] intArray = ArrayUtils.toPrimitive(temp.toArray(new Integer[0]));

你可能踩过的坑

很多人失败是因为直接用temp.toArray()强转成int[],这会抛出ClassCastException——因为toArray()返回的是Object[],而Object[]不能直接强制转换为int[],必须先转成Integer[]再处理。

内容的提问来源于stack exchange,提问作者BigDaddySam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:25:34