HashMap 避免冲突的 Java 示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11727811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:09:51  来源:igfitidea点击:

HashMap Java example to avoid collision

javahashmap

提问by Tony

I am using HashMapin 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.

HashMap在 java 中使用来存储密钥和Object <Key,Object>. 我阅读了有关 hashmap 冲突的信息,并试图通过使用链表来避免它。

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?

有人可以指出我使用链表实现哈希图的在线资源吗?

回答by Chris Dargis

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.

Java HashMap 已经以这种方式为您处理冲突。您需要做的就是确保您覆盖并实现了密钥hashCode()equals()方法。

Each hash codewill map to a specific "bucket". Each bucket contains a linked list for the case of collisions.

每个都hash code将映射到特定的“存储桶”。每个桶都包含一个用于冲突情况的链表。

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.

避免(或更确切地说,最小化)冲突的唯一方法是创建一个散列函数,该函数在整个 HashMap 中创建可能的最佳值分布。根据 HashMap 的密度和 的质量hash code,冲突几乎是不可避免的,因此需要覆盖这两种方法。

Edit: The OP asked for an example

编辑:OP要求举个例子

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;
  }
}

回答by Victor

The collision only occurs if you use the same objectas key, or different objectas keys with the same hash codeand equals.

仅当您使用相同的object键或不同的object具有相同哈希码等于的键时才会发生冲突。

For using correctly a HashMap, you should implement correctly in your key class the hashCode and equals method. Read the Object docs and this article.

为了正确使用 HashMap,您应该在键类中正确实现 hashCode 和 equals 方法。阅读 Object 文档和这篇文章

If you want to store more than one object by key, you should create a HashMap of list.

如果要按键存储多个对象,则应创建列表的 HashMap。

This is a simple example:

这是一个简单的例子:

HashMap<Object, List<Object>> map = new HashMap<Object, List<Object>>();
map.put(key, new LinkedList<Object>);
map.get(key).add(object);