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

Java如何将两个ArrayList合并为对应位置元素配对的二维列表

问题原因

你当前的写法直接把两个单值逐个添加到最终列表中,所以会得到平铺的一维列表;另外复用同一个临时列表后调用clear的写法存在错误,Java中集合为引用传递,添加到父集合后修改原集合,父集合中存储的对应元素也会同步变更。

正确实现

以Java语言为例,可按以下方式实现:

方式1:结果集合元素为int数组

import java.util.ArrayList;
import java.util.List;

public class MergeList {
    public static void main(String[] args) {
        List<Integer> newList3 = List.of(-50, 30, -20, 0, 20, -30, 50);
        List<Integer> newList4 = List.of(1, 1, 1, 1, 1, 1, 1);
        List<int[]> result = new ArrayList<>();
        // 先校验两个列表长度一致,避免索引越界
        if (newList3.size() != newList4.size()) {
            throw new IllegalArgumentException("两个输入列表长度必须相等");
        }
        for (int i = 0; i < newList3.size(); i++) {
            // 每次循环生成新的数组存入结果集合
            result.add(new int[]{newList3.get(i), newList4.get(i)});
        }
    }
}

方式2:结果集合元素为List

如果需要子元素也是列表类型,每次循环新建独立的临时列表即可,不要复用同一个对象:

List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < newList3.size(); i++) {
    List<Integer> tempList = new ArrayList<>();
    tempList.add(newList3.get(i));
    tempList.add(newList4.get(i));
    result.add(tempList);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:39:03