Home  >  Article  >  Java  >  How to use hashCode method in Java

How to use hashCode method in Java

WBOY
WBOYforward
2023-05-11 13:49:061735browse

1. Introduce the hashCode method

  • hashCode() The function is to obtain the hash code, also called hash code, it actually returns An integer. The purpose of this hash code is to determine the index position of the object in the hash table.

  • hashCode() is defined in Object.java of JDK, which means that any class in Java contains hashCode() function.

  • The hash table stores key-value pairs. Its characteristic is that it can quickly retrieve the corresponding "value" according to the "key". This uses hash codes! (You can quickly find the object you need).

2. Why is the hashCode method needed?

In the process of writing programs, judging whether two objects are the same is a very common and often faced problem. The hashCode() method is used to improve the speed of comparing two objects.

Let's take "How to check duplicates in HashSet" as an example to explain why hashCode is needed:

  • When you add an object to HashSet, HashSet will first calculate the hashcode value of the object to determine the location where the object is added. It will also compare it with the hashcode value of other objects that have been added. If there is no matching hashcode , HashSet will assume that the object does not appear repeatedly.

  • But if an object with the same hashcode value is found, the equals() method will be called to check whether the hashcode equal objects are true. of the same. If the two are the same, HashSet will not allow the join operation to succeed. If different, it will be rehashed to another location.

  • In this way we greatly reduce the number of equals, and accordingly greatly increase the execution speed.

3. What is the relationship between the two methods hashCode() and equals()?

Java stipulates the eqauls() method and hashCode() method as follows:

  • Calling the hashCode() method multiple times on the same object always returns the same integer value.

  • If a.equals(b), then a.hashCode() must be equal to b.hashCode().

  • If !a.equals(b), then a.hashCode() is not necessarily equal to b.hashCode(). At this time, if a.hashCode() is always not equal to b.hashCode(), the performance of hashtables will be improved.

  • a.hashCode()==b.hashCode() then a.equals(b) can be true or false

  • a.hashCode ()! = b.hashCode() then a.equals(b) is false.

A brief summary of the above conclusion:

  • If two objects equals, the Java runtime environment will think that their hashCode must be equal.

  • If two objects are not equals, their hashCode may be equal.

  • If the hashCode of two objects are equal, they are not necessarily equals.

  • If the hashCode of two objects are not equal, they must not be equals.

4. Why must overriding the equals method override the hashcode method ?

  • We explained above that if two objects are equals, then their hashCode values ​​must be equal. If you only override the equals method without overriding the hashCode method, the value of hashCode will be different, and the equals method will The determined result is true.

  • In some containers in Java, two identical objects are not allowed. When inserting, if they are judged to be the same, they will be overwritten. At this time, if you only rewrite the equals method without rewriting the hashCode method, the hashCode in the Object is formed based on the storage address conversion of the object. A hash value. At this time, it is possible that the hashCode method is not overridden, causing the same object to be hashed to different locations, resulting in the problem that the object cannot be overwritten.

For example

Dog class

package com.xiao;

/**
 * @author :小肖
 * @date :Created in 2022/3/11 14:42
 */
public class Dog {

    private String name;

    private Integer age;


    public Dog() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Dog(String name, Integer age) {
        this.name = name;
        this.age = age;
    }


    @Override
    public boolean equals(Object obj) {
        if(obj.getClass() != getClass()){
            return false;
        }
        Dog dog = (Dog) obj;
        if(dog.getAge() == age && dog.getName().equals(name)){
            return true;
        }
        return false;
    }
}

Test class

import com.xiao.Dog;

public class Test {

    public static void main(String[] args) {
        Dog dog = new Dog("小旺",2);
        Dog dog1 = new Dog("小旺",2);
        System.out.println("equals结果:" + dog.equals(dog1));
        System.out.println("dog 的 hashCode 值是否等于 dog1 的 hashCode 值:" +(dog.hashCode() == dog1.hashCode()));
    }
}

Test result

equals result : Is the hashCode value of true
dog equal to the hashCode value of dog1: false

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

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete