哈希表 03 Java中的hashCode

本文深入探讨了Java中hashCode()和equals()方法的工作原理,解释了如何自定义这两个方法来确保对象的正确比较和哈希值的一致性。通过一个具体的Student类示例,详细说明了哈希函数的实现及解决哈希冲突的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 在Java中,如果不显示的覆盖类的hashCode()方法,Java默认的hashCode()方法是根据对象在内存中的地址返回了一个整数值;
  • 也就是说,相同的对象(每个属性值都相等),hashCode可能是不一样的;
public class Student {

    int grade;
    int cls;
    String firstName;
    String lastName;

    Student(int grade, int cls, String firstName, String lastName){
        this.grade = grade;
        this.cls = cls;
        this.firstName = firstName;
        this.lastName = lastName;
    }

}

哈希函数

  • 自定义的生成hashCode的方法;
@Override
public int hashCode(){

    int B = 31;
    int hash = 0;
    hash = hash * B + ((Integer)grade).hashCode();
    hash = hash * B + ((Integer)cls).hashCode();
    hash = hash * B + firstName.toLowerCase().hashCode();
    hash = hash * B + lastName.toLowerCase().hashCode();
    return hash;

}

解决哈希冲突的方法

  • 当两个对象的hashCode相等的时候,通过这个方法解决哈希冲突;
@Override
public boolean equals(Object o){

    if(this == o)
        return true;

    if(o == null)
        return false;

    if(getClass() != o.getClass())
        return false;

    Student another = (Student)o;
    return this.grade == another.grade &&
            this.cls == another.cls &&
            this.firstName.toLowerCase().equals(another.firstName.toLowerCase()) &&
            this.lastName.toLowerCase().equals(another.lastName.toLowerCase());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值