HashMap重复键问题咨询:一对多映射场景下的代码修复方案
修复HashMap单键多值绑定问题的方案
你的核心问题是HashMap<Integer, Integer>无法让单个键关联多个值,重复调用put会覆盖之前的值(比如你给键1先后存2和9,最终只会保留9)。下面是两种可行的修复方案,同时修正你代码里的数组越界小问题:
方案一:使用HashMap<Integer, List<Integer>>(原生Java实现,无需额外依赖)
把Map的value类型改成列表,让每个键对应一个索引列表,这样就能绑定多个值了。修改后的完整代码如下:
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MatrixMapper { public static void main(String[] args) { // 键对应索引列表,实现单键多值映射 Map<Integer, List<Integer>> numberInput = new HashMap<>(); // 给键1添加两个索引:2和9 numberInput.computeIfAbsent(1, k -> new ArrayList<>()).add(2); numberInput.computeIfAbsent(1, k -> new ArrayList<>()).add(9); // 键2添加索引3 numberInput.computeIfAbsent(2, k -> new ArrayList<>()).add(3); // 键7添加索引8 numberInput.computeIfAbsent(7, k -> new ArrayList<>()).add(8); int[][] matrix = new int[10][10]; // 遍历矩阵的行(对应输入的行号1-10,对应数组索引0-9) for (int rowNum = 1; rowNum <= matrix.length; rowNum++) { List<Integer> indices = numberInput.get(rowNum); if (indices != null) { for (int idx : indices) { // 输入的索引是1-based,转成数组0-based索引 int colIndex = idx - 1; // 确保索引在矩阵范围内,避免越界 if (colIndex >= 0 && colIndex < matrix[rowNum - 1].length) { matrix[rowNum - 1][colIndex] = 1; } } } } // 打印矩阵 for (int[] row : matrix) { for (int num : row) { System.out.print(num); } System.out.println(); } } }
关键修改点:
- 把Map类型改为
Map<Integer, List<Integer>>,每个键对应一个索引列表 - 用
computeIfAbsent简化操作:如果键不存在,自动创建新的ArrayList,再添加索引值,避免手动判断空指针 - 修正原代码的数组越界问题:原代码中
i从0开始,i-1会导致行索引为-1,现在直接用1-based的行号遍历,转成数组0-based索引更直观 - 添加索引范围校验,防止输入的索引超出矩阵列数
方案二:使用Guava的Multimap(需引入第三方库)
如果项目中已经使用Guava库,可以直接用Multimap,它原生支持单键多值映射,代码更简洁:
import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; public class MatrixMapperGuava { public static void main(String[] args) { Multimap<Integer, Integer> numberInput = ArrayListMultimap.create(); numberInput.put(1, 2); numberInput.put(1, 9); numberInput.put(2, 3); numberInput.put(7, 8); int[][] matrix = new int[10][10]; for (Map.Entry<Integer, Integer> entry : numberInput.entries()) { int rowNum = entry.getKey(); int idx = entry.getValue(); int rowIndex = rowNum - 1; int colIndex = idx - 1; if (rowIndex >= 0 && rowIndex < matrix.length && colIndex >=0 && colIndex < matrix[rowIndex].length) { matrix[rowIndex][colIndex] = 1; } } // 打印矩阵 for (int[] row : matrix) { for (int num : row) { System.out.print(num); } System.out.println(); } } }
说明:
ArrayListMultimap会自动为每个键维护一个ArrayList,无需手动处理列表的创建和添加,适合快速开发。
内容的提问来源于stack exchange,提问作者Umseizure
相关产品推荐
相关产品推荐

