Home > Java > javaTutorial > body text

Detailed introduction to the role of hashCode in Java

黄舟
Release: 2017-03-29 10:38:31
Original
1433 people have browsed it

This article mainly introduces relevant information that explains the function of hashCode in Java in detail. Friends who need it can refer to

Detailed explanation of the function of hashCode in Java

as follows It is the official document definition of HashCode:

hashcode方法返回该对象的哈希码值。支持该方法是为哈希表提供一些优点,例如,java.util.Hashtable 提供的哈希表。  
 
hashCode 的常规协定是:  
在 Java 应用程序执行期间,在同一对象上多次调用 hashCode 方法时,必须一致地返回相同的整数,前提是对象上 equals 比较中所用的信息没有被修改。
从某一应用程序的一次执行到同一应用程序的另一次执行,该整数无需保持一致。  
如果根据 equals(Object) 方法,两个对象是相等的,那么在两个对象中的每个对象上调用 hashCode 方法都必须生成相同的整数结果。  
以下情况不 是必需的:如果根据 equals(java.lang.Object) 方法,两个对象不相等,那么在两个对象中的任一对象上调用 hashCode 方法必定会生成不同的整数结果。
但是,程序员应该知道,为不相等的对象生成不同整数结果可以提高哈希表的性能。  
实际上,由 Object 类定义的 hashCode 方法确实会针对不同的对象返回不同的整数。
(这一般是通过将该对象的内部地址转换成一个整数来实现的,但是 JavaTM 编程语言不需要这种实现技巧。)  
 
当equals方法被重写时,通常有必要重写 hashCode 方法,以维护 hashCode 方法的常规协定,该协定声明相等对象必须具有相等的哈希码。
Copy after login

We can extract the above definition of the official document into the following key points:

1. The existence of hashCode is mainly used For the speed of search, such as Hashtable, HashMap, etc., hashCode is used to determine the storage address of the object in the hash storage structure;
2. If the two objects are the same, equals(Java.lang.Object ) method, then the hashCode of the two objects must be the same;
3. If the equals method of the object is rewritten, then the hashCode of the object should also be rewritten as much as possible, and the object used to generate the hashCode must be the same as in the equals method. Use them consistently, otherwise it will violate point 2 mentioned above;
4. The same hashCode of two objects does not necessarily mean that the two objects are the same, that is, it does not necessarily apply to equals (Java.lang. Object) method can only indicate that these two objects are in a hash storage structure, such as Hashtable, and they are "stored in the same basket".

To summarize, hashCode is used for searching, while equals is used to compare whether two objects are equal. The following paragraph is copied from a reply to someone else's post:

1.hashcode是用来查找的,如果你学过数据结构就应该知道,在查找和排序这一章有 
例如内存中有这样的位置 
0 1 2 3 4 5 6 7  
而我有个类,这个类有个字段叫ID,我要把这个类存放在以上8个位置之一,如果不用hashcode而任意存放,那么当查找时就需要到这八个位置里挨个去找,或者用二分法一类的算法。 
但如果用hashcode那就会使效率提高很多。 
我们这个类中有个字段叫ID,那么我们就定义我们的hashcode为ID%8,然后把我们的类存放在取得得余数那个位置。
比如我们的ID为9,9除8的余数为1,那么我们就把该类存在1这个位置,如果ID是13,求得的余数是5,那么我们就把该类放在5这个位置。
这样,以后在查找该类时就可以通过ID除 8求余数直接找到存放的位置了。 
 
2.但是如果两个类有相同的hashcode怎么办那(我们假设上面的类的ID不是唯一的),例如9除以8和17除以8的余数都是1,
那么这是不是合法的,回答是:可以这样。那么如何判断呢?在这个时候就需要定义 equals了。 
也就是说,我们先通过 hashcode来判断两个类是否存放某个桶里,但这个桶里可能有很多类,那么我们就需要再通过 equals 来在这个桶里找到我们要的类。 
那么。重写了equals(),为什么还要重写hashCode()呢? 
想想,你要在一个桶里找东西,你必须先要找到这个桶啊,你不通过重写hashcode()来找到桶,光重写equals()有什么用啊
Copy after login

Finally, let's look at a specific example,

public class HashTest { 
  private int i; 
 
  public int getI() { 
    return i; 
  } 
 
  public void setI(int i) { 
    this.i = i; 
  } 
 
  public int hashCode() { 
    return i % 10; 
  } 
 
  public final static void main(String[] args) { 
    HashTest a = new HashTest(); 
    HashTest b = new HashTest(); 
    a.setI(1); 
    b.setI(1); 
    Set<HashTest> set = new HashSet<HashTest>(); 
    set.add(a); 
    set.add(b); 
    System.out.println(a.hashCode() == b.hashCode()); 
    System.out.println(a.equals(b)); 
    System.out.println(set); 
  } 
}
Copy after login

The output result:

true 
false 
[com.ubs.sae.test.HashTest@1, com.ubs.sae.test.HashTest@1]
Copy after login

In the above example, we only overridden the hashCode method. From the above results, we can see that although the hashCode of the two objects are equal, the two objects are not actually equal; if we did not override the equals method, then it will be called The default equals method of object is to compare whether the references of two objects are the same, indicating that they are two different objects, and the references of the two objects are definitely uncertain. Here we put the generated object into a HashSet, and a HashSet can only store a unique object, that is, only one object of the same type (applicable to the equals method) can be stored, but here there are actually two objects a and b. Was placed in HashSet, so HashSet loses its own meaning.

At this time we add the equals method:

public class HashTest { 
  private int i; 
 
  public int getI() { 
    return i; 
  } 
 
  public void setI(int i) { 
    this.i = i; 
  } 
 
  <span style="color:#3366FF;"><strong>public boolean equals(Object object) { 
    if (object == null) { 
      return false; 
    } 
    if (object == this) { 
      return true; 
    } 
    if (!(object instanceof HashTest)) { 
      return false; 
    } 
    HashTest other = (HashTest) object; 
    if (other.getI() == this.getI()) { 
      return true; 
    } 
    return false; 
  }</strong></span> 
 
  public int hashCode() { 
    return i % 10; 
  } 
 
  public final static void main(String[] args) { 
    HashTest a = new HashTest(); 
    HashTest b = new HashTest(); 
    a.setI(1); 
    b.setI(1); 
    Set<HashTest> set = new HashSet<HashTest>(); 
    set.add(a); 
    set.add(b); 
    System.out.println(a.hashCode() == b.hashCode()); 
    System.out.println(a.equals(b)); 
    System.out.println(set); 
  } 
}
Copy after login

The result obtained at this time will be as follows:

true 
true 
[com.ubs.sae.test.HashTest@1]
Copy after login

We can see from the result that now The two objects are completely equal, and only one object is stored in the HashSet.

The above is the detailed content of Detailed introduction to the role of hashCode in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!