Dan*_*l K 5 java hashmap hashcode collision
我正在尝试解决这个问题:
给定只有3个唯一数字的整数数组,它们会在O(n)时间中按升序(以及它们各自的频率)打印数字。
我想不使用counting sort
算法来解决它,所以我想我可以做一个,for loop
然后将数字插入a HashMap
,然后loop
通过HashMap entrySet
并打印所需的信息。
这是函数:
public static void printOut(int[] arr){
Map<Integer,Integer> hm=new HashMap<Integer,Integer>();
for(int num : arr){
if(hm.containsKey(num)){
hm.put(num,hm.get(num)+1);
}else{hm.put(num,1);}
}
for(Map.Entry<Integer,Integer> entry : hm.entrySet()){
System.out.println("Key= "+entry.getKey()+" Value= "+entry.getValue());
}
}
Run Code Online (Sandbox Code Playgroud)
当我的数组是时,这就是窍门: [3, 3, 2, 1, 3, 2, 1]
但是上面的数组不应导致任何冲突,因此我尝试使用应该导致冲突的数组,我测试过我的函数的数组之一是:[6,6,9,9,6,3,9]
但是我的函数仍然Keys
按升序打印,这让我感到困惑,因为我以为当的Key
of HashMap
是一个整数时,哈希码应该是hashIndex = key % noOfBuckets
这样,当我有数字时6, 9 and 3
,我HashMap keys
以为会发生冲突,并且我的函数应该打印(基于上面使用的数组):
Key= 6 Value= 3
Key= 9 Value= 3
Key= 3 Value= 1
Run Code Online (Sandbox Code Playgroud)
但改为打印:
Key= 3 Value= 1
Key= 6 Value= 3
Key= 9 Value= 3
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释为什么我要解决我要解决的问题而不是我期望的答案的正确方法吗?
谢谢。
小智 8
归档时间: |
|
查看次数: |
316 次 |
最近记录: |