.equals()、.hashcode()和==之间的联系与差异

本文深入探讨Java中对象的equals与hashcode方法,解释它们的默认行为及重写原则,尤其关注如何通过重写解决对象去重问题,确保逻辑一致性和hashset的有效性。

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

在说这个问题之前,我先说一下几个概念

  • 内存地址:存放对象的物理地址
  • hashcode: hashcode是jvm为对象生成的一个int类型的数,并且保证在同一个jvm中,对于同一个对象每次返回的都是同一个hashcode(具体生成方式请看hashcode详解)
  • hash冲突:hashcode发生重复

我们先看看在Object中是怎样定义.equals()和.hashcode()的

public boolean equals(Object obj) {
        return (this == obj);
    }
public native int hashCode();

我们可以看到equals方法实际上是调用了 == 方法,而 == 是比较对象的内存地址。所以默认的equals方法是比较的内存地址。
hashcode在1.8中的生成其实是和内存地址无关的,它和线程以及对象生成的顺序有关(具体生成方式请看hashcode详解

在Object中的.equals()和.hashCode()方法并不能很好的解决生活中的一些问题,比如说,我们new了两个学生对象,学生的id和name都是一样的,在jvm中会认为这是两个对象,可在现实生活中我们却认为这是同一个对象,于是这里出现了歧义,为了解决这种歧义我们需要重写.equals()方法。

public class Student {
    private int id;
    private String name;

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Student))
            return false;
        Student s= (Student) obj;
        if (id==s.id && name.equals(s.name))
            return true;
        return false;
    }

    public static void main(String[] args) {
        Student student1=new Student(1,"张三");
        Student student2=new Student(1,"张三");
        System.out.println(student1==student2);
        System.out.println(student1.equals(student2));
    }
}

运行结果:
false
true

结果看起来很完美,通过重写equals方法,已经做到了辨认学生的目的。

假如我们遇到了要把学生去重的场景,最简单的办法就是把学生对象丢进一个set里面然后再拧出来,我们来看看结果会怎么样?

public class Student {
    private int id;
    private String name;

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Student))
            return false;
        Student s= (Student) obj;
        if (id==s.id && name.equals(s.name))
            return true;
        return false;
    }

    public static void main(String[] args) {
        Student student1=new Student(1,"张三");
        Student student2=new Student(1,"张三");
        System.out.println(student1==student2);
        System.out.println(student1.equals(student2));
        HashSet<Student> set=new HashSet<Student>();
        set.add(student1);
        set.add(student2);
        System.out.println(set.size());
    }
}

输出是
false
true
2

发现并没有去重,为什么呢?因为java中我们最常用的set是hashset,hashset实际上就是没有value的hashmap,他会先把对象的hashcode按照一定的算法定位到一个数组元素上去,如果这个数组上有元素就会进行比较,相同就替换,不同就挂载到下面,因为这两个student的hashcode是不同的,所以这两个student就被定位到不同的数组元素上去了,所以就被认为是两个独立的对象。(hashmap原理

这种情况下我们可以对hashcode进行重写,让拥有相同id和name的student都拥有相同的hashcode

public class Student {
    private int id;
    private String name;

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Student))
            return false;
        Student s= (Student) obj;
        if (id==s.id && name.equals(s.name))
            return true;
        return false;
    }

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

    public static void main(String[] args) {
        Student student1=new Student(1,"张三");
        Student student2=new Student(1,"张三");
        System.out.println(student1==student2);
        System.out.println(student1.equals(student2));
        HashSet<Student> set=new HashSet<Student>();
        set.add(student1);
        set.add(student2);
        System.out.println(set.size());

    }
}

结果如下
false
true
1

通过重写hashcode和equals方法我们可以解决实际问题中jvm和人类认知对象不同的差异。

hashcode是一个int类型的,大小是2^32-1,而对象却可以是无穷无尽的,因此可以推断出hashcode是有可能发生重复的,这种重复我们就称之为hash冲突。

一个好的hash算法应该尽量的去避免这种冲突。

我们用的很多类其实都已经重写了hashcode和equals方法,我详细来分析一下String类型

//String实际是一个final修饰的char数组
 private final char value[];
 //实际上是一个hash的缓存
 private int hash;
  public boolean equals(Object anObject) {
  		//先判断内存地址是否相等,是就返回true
        if (this == anObject) {
            return true;
        }
        //再判断要比较的对象是否是String类型,是就往下走,不是就返回false
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            //先比较长度,长度不对返回false
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                //直接比较对应字符,如果全部相等才会返回true
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
    public int hashCode() {
        int h = hash;
       //缓存没有  并且有值才会去生成hashcode  
        if (h == 0 && value.length > 0) {
            char val[] = value;
			//每一个char都会参与运算,保证同一个String 即使内存地址不一样 返回的hashcode都是一样的
            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

由于String的hashCode的生成只与内容有关,而与其它因素无关,所以相同内容的String在任何机器上生成的hashcode都是一致的。这个特性我们运用得很多,比如说对数据库进行拆分,我们把某个列对hash取模,然后把数据分到不同机器上的不同的数据库中去,然后要取数据的时候,在对hash进行取模来决定要去哪个数据库去取值。

ok,我们来总结一下:
.equals()在Object中与 == 是等价的,但是.equals()在语义上是对象的内容相等,因此很多时候都会对.equals()进行重写,而 == 则是对内存地址进行比较而不关心对象内容。

.hashcode()的存在则是为了便于我们对对象的操作,比如说使用hash算法来加速数据的存取,原则上来说,我们应该保证.equals()相等的对象的.hashcode()也是相等的,反之则不需要保证。因此在必要的时候我们要对hashcode进行重写。

hashcode实质上是一个int类型的数,hashcode是可以重复的。

``` @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Address)) return false; Address address1 = (Address) o; if (getAid() != null ? !getAid().equals(address1.getAid()) : address1.getAid() != null) return false; if (getUid() != null ? !getUid().equals(address1.getUid()) : address1.getUid() != null) return false; if (getName() != null ? !getName().equals(address1.getName()) : address1.getName() != null) return false; if (getProvinceName() != null ? !getProvinceName().equals(address1.getProvinceName()) : address1.getProvinceName() != null) return false; if (getProvinceCode() != null ? !getProvinceCode().equals(address1.getProvinceCode()) : address1.getProvinceCode() != null) return false; if (getCityName() != null ? !getCityName().equals(address1.getCityName()) : address1.getCityName() != null) return false; if (getCityCode() != null ? !getCityCode().equals(address1.getCityCode()) : address1.getCityCode() != null) return false; if (getAreaName() != null ? !getAreaName().equals(address1.getAreaName()) : address1.getAreaName() != null) return false; if (getAreaCode() != null ? !getAreaCode().equals(address1.getAreaCode()) : address1.getAreaCode() != null) return false; if (getZip() != null ? !getZip().equals(address1.getZip()) : address1.getZip() != null) return false; if (getAddress() != null ? !getAddress().equals(address1.getAddress()) : address1.getAddress() != null) return false; if (getPhone() != null ? !getPhone().equals(address1.getPhone()) : address1.getPhone() != null) return false; if (getTel() != null ? !getTel().equals(address1.getTel()) : address1.getTel() != null) return false; if (getTag() != null ? !getTag().equals(address1.getTag()) : address1.getTag() != null) return false; return getIsDefault() != null ? getIsDefault().equals(address1.getIsDefault()) : address1.getIsDefault() == null; } @Override public int hashCode() { int result = getAid() != null ? getAid().hashCode() : 0; result = 31 * result + (getUid() != null ? getUid().hashCode() : 0); result = 31 * result + (getName() != null ? getName().hashCode() : 0); result = 31 * result + (getProvinceName() != null ? getProvinceName().hashCode() : 0); result = 31 * result + (getProvinceCode() != null ? getProvinceCode().hashCode() : 0); result = 31 * result + (getCityName() != null ? getCityName().hashCode() : 0); result = 31 * result + (getCityCode() != null ? getCityCode().hashCode() : 0); result = 31 * result + (getAreaName() != null ? getAreaName().hashCode() : 0); result = 31 * result + (getAreaCode() != null ? getAreaCode().hashCode() : 0); result = 31 * result + (getZip() != null ? getZip().hashCode() : 0); result = 31 * result + (getAddress() != null ? getAddress().hashCode() : 0); result = 31 * result + (getPhone() != null ? getPhone().hashCode() : 0); result = 31 * result + (getTel() != null ? getTel().hashCode() : 0); result = 31 * result + (getTag() != null ? getTag().hashCode() : 0); result = 31 * result + (getIsDefault() != null ? getIsDefault().hashCode() : 0); return result; }```equals()and hashCode,为什么我创建的时候这个不一样
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值