当前位置:网站首页>Relationship between hashcode() and equals()

Relationship between hashcode() and equals()

2022-07-06 13:41:00 Wake up duck, did you program today?

stay java in , Each object can call its own hashcode() Method to get its own hash value

  • If I have two objects hashcode inequality , Then these two objects must be different objects
  • If I have two objects hashcode identical , It does not mean that these two objects must be the same object , It can also be two objects
  • If two objects are equal , So their hashCode It must be the same

stay java In the implementation class of some collection classes , When comparing whether two objects are equal , According to the above principles , Will call the object first hashCode() Method to get hashCode Compare , If hashCode If you are different, you can directly think that the two objects are different , If hashCode Same value , Then it will call further equals() Methods for comparison , and equals() Method , It is used to finally determine whether two objects are equal , Usually equals Implementation will be heavy , More logic , and hashCode() The main thing is to get a hash value , It's actually a number , Relatively light , So when comparing two objects , Usually use it first hashCode

Be careful : We rewrote equals() Method , Then pay attention to hashCode() Method , Be sure to follow the above rules .

Here's the picture :

package com.ws;

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<User,String> hashMap = new HashMap<>();
        hashMap.put(new User("wangshun"),"123");
        System.out.println(hashMap.get(new User("wangshun")));
    }
}
class User {
    private String name;

    public User(String name) {
        this.name = name;
    }
    public String getName(){
        return name;
    }

    @Override
    public boolean equals(Object obj) {
        User user = (User) obj;
        return user.getName().equals(this.name);
    }

}

No rewriting hashcode The previous running result is null

package com.ws;

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<User,String> hashMap = new HashMap<>();
        hashMap.put(new User("wangshun"),"123");
        System.out.println(hashMap.get(new User("wangshun")));
    }
}
class User {
    private String name;

    public User(String name) {
        this.name = name;
    }
    public String getName(){
        return name;
    }

    @Override
    public boolean equals(Object obj) {
        User user = (User) obj;
        return user.getName().equals(this.name);
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }
}

rewrite hashcode For after 123

原网站

版权声明
本文为[Wake up duck, did you program today?]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060916451664.html