我的代码有什么问题?我正在尝试打印密钥,但是当我打印时,我得到了重复的密钥。我的印象是,当我们向 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
这不是你的打印循环位置错误的问题吗?
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() + " ");
}
}
}
您获得的输出是在 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() + " ");
}
}
}
2=1
9=1
10=3
12=1
45=2
现在,如果将最后一个循环移到第一个循环之外,您将得到以下结果。
10 45