重写hashcode和equals

重写hashcode和equals

例如:

public class Person {
    private String name;
    private int age;
}
  1. hashcode

    定义初始值37,然后每次乘31加上属性值的hashcode方法。

    public int hashcode() {
        int res = 37;
        
        res = 31 * res + (name != null?) name.hashcode(): 0;
        res = 31 * res + (age != null?) age.hashcode(): 0;
        
        return res;
    }
    

    还可以直接调用Objects.hashcode()

    public int hashcode() {
        int res = Objects.hash(name, age);
    }
    

    但是注意:如果有了数组对象,需要对数组对象的所有内容单独调用hash,否则会有问题。

    因为数组本身和数组本身是不同的,但是数组的元素相同,意思是:

    int[] a = {1, 2};
    int[] b = {1, 2};
    System.out.println(a.hashCode());
    System.out.println(b.hashCode());
    
    // 结果:
    681842940
    1392838282
        
    // 但是如果把每个元素都计算
    System.out.println(ArrayHashCode(a));
    System.out.println(ArrayHashCode(b));
    
    public static int ArrayHashCode(int[] arr) {
        int res = 37;
    
        for (int i : arr) {
            res = res * 31 + Integer.hashCode(i);
        }
    
        return res;
    }
    
    // 结果
    35590
    35590
        
    // 或者可以使用Arrays.hashcode()
    
  2. equals

    1. 先判断是否指向的是同一个内存地址
    2. 在判断是否为空,或者类型不相同
    3. 如果类型相同,直接强制类型转换,比较属性值是否相同即可。
    public boolean equals(Person that) {
        if (this == that) return true;
        if (that == null || that.getClass() != this.getClass()) return false;
        
        Person p = (Person) that;
        
        if (this.age != p.age) return false;
        
        return this.name == null?
            	that.name == null:
        		this.name.equals(that.name);
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值