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

Java中如何将数组添加到存储数组类型的ArrayList集合中

你的ArrayList<int[]> cartelle本身的元素类型就是int数组,不需要做复杂转换,直接调用add方法即可存入指定数组:

// 已有定义
ArrayList<int[]> cartelle = new ArrayList<>();
int[] cartella = new int[NUMERICARTELLA];

// 直接存入数组
cartelle.add(cartella);

你之前操作报错的原因

  • 误用Arrays.asList():该方法传入int数组时,会将整个数组作为单个元素返回List<int[]>类型对象,不仅多此一举,且该方法返回的是Arrays内部的固定长度List实现,并非java.util.ArrayList,如果强转还会抛出类型转换异常。
  • 调用setCartelle()报错:该方法的入参要求是ArrayList<int[]>类型,你直接传入单个int[]自然类型不匹配。如果需要给该属性赋值,可先把数组存入集合后再传入:
// 方式1:使用已有的cartelle集合
cartelle.add(cartella);
giocatori.get(i).setCartelle(cartelle);

// 方式2:仅存入当前单个数组,新创建临时集合
ArrayList<int[]> tempList = new ArrayList<>();
tempList.add(cartella);
giocatori.get(i).setCartelle(tempList);

额外注意

存入ArrayList的是数组的引用,后续你修改cartella数组内部的元素值,集合中存储的对应数组也会同步更新。如果需要存储独立副本,存入前先做数组拷贝即可:

int[] cartellaCopy = Arrays.copyOf(cartella, cartella.length);
cartelle.add(cartellaCopy);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 05:36:05