欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实体类中equals和hashCode方法的重写

程序员文章站 2022-04-12 22:08:55
public class User{ private int id; private String name; private int age; setget方法 @Override public boolean equals(Object obj) { if (obj == null){ return false; } if (this == obj){ ......

public class User{
 
    private int id;
 
    private String name;
 
    private int age;

    setget方法

    @Override
    public boolean equals(Object obj) {
        if (obj == null){
            return false;
        }
        if (this == obj){
            return true;
        }
     
         if (obj instanceof User){
            User user = (User)obj;
            if (user.getId().equals(this.id) && user.getName().equals(this.name) && user.getAge().equals(this.age)){
                return true;
            }
        }
        return super.equals(obj);
    }
 
    @Override
    public int hashCode() {
        int result;
        result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + age;
        return result;
    }
}

 

为什么使用31 ,hashCode源码

 /**
     * Returns a hash code for this string. The hash code for a
     * {@code String} object is computed as
     * <blockquote><pre>
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * </pre></blockquote>
     * using {@code int} arithmetic, where {@code s[i]} is the
     * <i>i</i>th character of the string, {@code n} is the length of
     * the string, and {@code ^} indicates exponentiation.
     * (The hash value of the empty string is zero.)
     *
     * @return  a hash code value for this object.
     */
    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;
 
            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

本文地址:https://blog.csdn.net/WangKun_0612/article/details/107672060