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

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
     *


     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     *

     * using {@code int} arithmetic, where {@code s[i]} is the
     * ith 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;
    }

你可能感兴趣的:(工作记录,hashcode,object,jdk,java)