equals方法用来比较两个对象是否为同一个对象
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