HashMap Java示例避免冲突 [英] HashMap Java example to avoid collision
问题描述
我在java中使用 HashMap
来存储密钥和 Object< Key,Object>
。我读到了关于hashmap碰撞的内容,我试图通过使用链表来避免它。
我在网上做了一些搜索,但我找不到一个例子怎么做这个。
有人可以指向我实现带链表的散列图的在线资源吗?
Java HashMap已经以这种方式为您处理冲突。您需要做的就是确保覆盖并实现密钥的 hashCode()
和 equals()
方法。 / p>
每个哈希码
将映射到特定的桶。每个存储桶都包含一个用于冲突情况的链接列表。
避免(或者更确切地说是最小化)冲突的唯一方法是创建一个哈希在整个HashMap中创建最佳值分布的函数。根据HashMap的密度和哈希码
的质量,冲突几乎是不可避免的,因此需要覆盖这两种方法。
编辑:OP要求提供示例
要覆盖这两种方法:
public class MyObject {
String var1;
int var2;
// ... ...
public boolean equals(Object obj){
if(obj == null)return false;
如果(this == obj)返回true; //引用相等
if(!(obj instanceof MyObject))返回false;
MyObject myObj = MyObject(obj);
return(var1.equals(myObj.var1))&& (var2 == myObj.var2);
}
public int hashCode {
return var1.hashCode()^ var2;
}
}
I am using HashMap
in java to store key and Object <Key,Object>
. And I read about hashmap collision and I am trying to avoid it by using linked list.
I did some search online, but I couldn't find an example how to do this.
Can somebody point me to an online resources that implement the hashmap with linked list?
The Java HashMap already handles collisions for you in this way. All you need to do is ensure you are overriding and implementing the key's hashCode()
and equals()
method.
Each hash code
will map to a specific "bucket". Each bucket contains a linked list for the case of collisions.
The only way to avoid (or rather minimize) collisions is to create a hash function that creates the best possible distribution of values throughout the HashMap. Depending on the density of your HashMap and the quality of your hash code
, collisions are almost inevitable, hence the need to override the two methods.
Edit: The OP asked for an example
To override the two methods:
public class MyObject {
String var1;
int var2;
//...
public boolean equals(Object obj) {
if(obj == null) return false;
if(this == obj) return true; // Reference equality
if(!(obj instanceof MyObject)) return false;
MyObject myObj = MyObject(obj);
return (var1.equals(myObj.var1)) && (var2 == myObj.var2);
}
public int hashCode {
return var1.hashCode() ^ var2;
}
}
这篇关于HashMap Java示例避免冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!