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

Java生成ArrayList无重复排列并存入HashMap分配ID结果异常

问题排查与修复方案

核心错误原因

  • 最外层多余循环:你套了一层i从1到maxTriplets的循环,整个排列生成逻辑会重复执行maxTriplets次,是最终输出数量异常的核心诱因。
  • 字符串比较逻辑错误:Java中==用于比较对象内存地址,比较字符串内容需要用equals方法,你的判断逻辑完全失效,导致大量带重复元素的错误排列被生成。
  • 去重规则错误:你对val3的判断条件为val3 == val1 & val3 == val2,仅当val3同时等于前两个值才跳过,实际上只要等于其中任意一个就属于重复元素需要排除。同时你在while循环中直接自增下标k、l,没有做边界校验,很容易触发数组越界异常。
  • 硬编码限制:当前代码写死了三层循环,仅支持3个元素的排列生成,无法扩展到任意长度的输入列表。

3元素场景快速修复代码

HashMap<String, Long> permutationAndID = new HashMap<>();
long id = 1;
int inputSize = inputs.size();
// 移除多余的外层i循环
for (int j = 0; j < inputSize; j++) {
    String val1 = String.valueOf(inputs.get(j));
    for (int k = 0; k < inputSize; k++) {
        String val2 = String.valueOf(inputs.get(k));
        // 排除和第一个元素重复的取值
        if (val2.equals(val1)) {
            continue;
        }
        for (int l = 0; l < inputSize; l++) {
            String val3 = String.valueOf(inputs.get(l));
            // 排除和前两个元素任意一个重复的取值
            if (val3.equals(val1) || val3.equals(val2)) {
                continue;
            }
            String permutation = val1 + "," + val2 + "," + val3;
            System.out.println("Permutation: [" + permutation + "] ID: " + id);
            permutationAndID.put(permutation, id);
            id++;
        }
    }
}
long maxTriplets = 6; // 3个元素的全排列数量为3!=6
if (permutationAndID.size() == maxTriplets) {
    System.out.println("\nAll " + maxTriplets + " permutations generated correctly!");
} else {
    System.out.println("\nAn error occured while generating the permutations!");
}

任意长度全排列通用实现(回溯法)

如果需要适配不同长度的输入列表,可以用回溯逻辑实现:

import java.util.concurrent.atomic.AtomicLong;

// 全排列递归生成方法
private void generatePermutation(List<Integer> inputs, List<Integer> currentPath, 
                                 boolean[] used, Map<String, Long> result, AtomicLong id) {
    // 当前排列长度等于输入长度时完成一组排列生成
    if (currentPath.size() == inputs.size()) {
        String permStr = currentPath.stream()
                .map(String::valueOf)
                .reduce((a, b) -> a + "," + b)
                .orElse("");
        result.put(permStr, id.getAndIncrement());
        return;
    }
    for (int i = 0; i < inputs.size(); i++) {
        // 跳过已经使用过的元素
        if (used[i]) {
            continue;
        }
        used[i] = true;
        currentPath.add(inputs.get(i));
        generatePermutation(inputs, currentPath, used, result, id);
        // 回溯撤销操作
        currentPath.remove(currentPath.size() - 1);
        used[i] = false;
    }
}

// 调用示例
HashMap<String, Long> permutationAndID = new HashMap<>();
AtomicLong idCounter = new AtomicLong(1);
generatePermutation(inputs, new ArrayList<>(), new boolean[inputs.size()], permutationAndID, idCounter);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:27:00