为什么当我循环遍历哈希图时会打印重复的键?

问题描述 投票:0回答:3

我的代码有什么问题?我正在尝试打印密钥,但是当我打印时,我得到了重复的密钥。我的印象是,当我们向 hashmap 添加重复的键时,它会替换以前的键。

我正在尝试打印数组中的所有重复元素。

public static void repeatingElements(int a[], int n) {
  HashMap<Integer, Integer> map = new HashMap<>();
  for (int i = 0; i < n; i++) {
    if (map.containsKey(a[i])) {
      map.put(a[i], map.get(a[i]) + 1);
    } else {
      map.put(a[i],1);
    }

    for (Map.Entry<Integer, Integer> entry: map.entrySet()) {
      if (entry.getValue()>1) {
        System.out.print(entry.getKey() + " ");
      }
    }
  }
}
  • 输入:
    {12, 10, 9, 45, 2, 10, 10, 45}
  • 预期输出:
    10 45
  • 我得到的输出:
    10 10 10 45
java arrays hashmap key-value
3个回答
0
投票

这不是你的打印循环位置错误的问题吗?

public static void repeatingElements(int a[], int n){
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i=0;i<n;i++){
            if(map.containsKey(a[i])){
                map.put(a[i], map.get(a[i]) + 1);
            }
            else {
                map.put(a[i],1);
            }
        }
        for(Map.Entry<Integer, Integer> entry: map.entrySet()){
            if(entry.getValue()>1){
                System.out.print(entry.getKey() + " ");
            }
        }
}

0
投票

您获得的输出是在 for 循环的每次迭代中发出 Map 状态的结果。

考虑每次迭代时 Map 的状态:

12: [{12:1}]  Output: 
10: [{12:1}, {10:1}] Output: 
 9: [{12:1}, {10:1}, {9:1}] Output: 
45: [{12:1}, {10:1}, {9:1}, {45:1}] Output: 
 2: [{12:1}, {10:1}, {9:1}, {45:1}, {2:1}] Output: 
10: [{12:1}, {10:2}, {9:1}, {45:1}, {2:1}] Output: 10
10: [{12:1}, {10:3}, {9:1}, {45:1}, {2:1}] Output: 10
45: [{12:1}, {10:3}, {9:1}, {45:2}, {2:1}] Output: 10 45

所以总输出最终为:10 10 10 45

解决方案是将状态输出移到循环之后。

public static void repeatingElements(int a[], int n){
  HashMap<Integer, Integer> map = new HashMap<>();
  for(int i=0;i<n;i++){
    if(map.containsKey(a[i])){
      map.put(a[i], map.get(a[i]) + 1);
    } else {
      map.put(a[i],1);
    }
  }
  for(Map.Entry<Integer, Integer> entry: map.entrySet()){
    if(entry.getValue()>1){
      System.out.print(entry.getKey() + " ");
    }
  }
}

    

0
投票
  • 对于第一次遇到的所有值,输入默认值 1。重复的键将替换当前值。
  • 找到每个键后,其值将被当前的一加 1 替换。
  • 最后,你的地图看起来像这样。
2=1
9=1
10=3
12=1
45=2

现在,如果将最后一个循环移到第一个循环之外,您将得到以下结果。

10 45 
© www.soinside.com 2019 - 2024. All rights reserved.