详解equals的用法以及和hashCode方法的联系

equals方法用来比较两个对象是否为同一个对象

  • 比较Integer包装类,只要值相等就返回true

Integer类重写了equals方法,我们通过源码可以看到只要两个对象的int值相等就会返回true

public boolean equals(Object obj) {
	if (obj instanceof Integer) {
	      return value == ((Integer)obj).intValue();
	  }
	return false;
}
Integer a = new Integer(10);
Integer b = new Integer(10);
Integer c = 10;
System.out.println(a.equals(b)); // true
System.out.println(a.equals(c)); // true
  • 比较自定义的对象时

自定义对象Phone

public class Phone {
	private String brand; // 品牌
	private String model; // 型号
	private int salary; // 价格

	public Phone(String brand, String model, int salary) {
		this.brand = brand;
		this.model = model;
		this.salary = salary;
	}
}

不重写equals方法时,可以看到Object类的源码,等同于==

public boolean equals(Object obj) {
	return (this == obj);
}
Phone phone1 = new Phone("华为", "p40", 3800);
Phone phone2 = new Phone("华为", "p40", 3800);
System.out.println(phone1 == phone2); // false
System.out.println(phone1.equals(phone2)); // false

右键直接生成equals和hashCode方法,重写后的比较和重写的方法逻辑有关,如下我生成的就比较的是实例对象,必须每个属性都一致才会返回true

public class Phone {
	private String brand; // 品牌
	private String model; // 型号
	private int salary; // 价格

	public Phone(String brand, String model, int salary) {
		this.brand = brand;
		this.model = model;
		this.salary = salary;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;
		Phone phone = (Phone) o;
		return salary == phone.salary &&
				brand.equals(phone.brand) &&
				model.equals(phone.model);
	}

	@Override
	public int hashCode() {
		return Objects.hash(brand, model, salary);
	}
}

equals方法比较两个对象相等,则两个对象的hashCode()方法的返回值必须一致

Phone phone1 = new Phone("华为", "p40", 3800);
Phone phone2 = new Phone("华为", "p40", 3800);
Phone phone3 = new Phone("华为", "p40", 3500);
System.out.println(phone1.equals(phone2)); // true
System.out.println(phone1.hashCode()); // 657989495
System.out.println(phone2.hashCode()); // 657989495
System.out.println(phone1.equals(phone3)); // false

但反过来,两个对象的hashCode()方法的返回值相等,两个对象的不一定相等
举个栗子,如下,我们改下hashCode()方法,hashCode值虽然一样,但可以看到equals比较结果为false

public int hashCode() {
	return this.salary * 30;
}
Phone phone1 = new Phone("华为", "p30", 3200);
Phone phone2 = new Phone("努比亚", "play", 3200);
System.out.println(phone1.hashCode()); // 96000
System.out.println(phone2.hashCode()); // 96000
System.out.println(phone1.equals(phone2)); // false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值