1.简述
" == " 比较的是值
" == " 如果比较的是基本数据类型,比较的则是变量值
" == " 如果比较的为引用数据类型,比较的则是地址值
equals比较的是引用数据类型
如果没有重写hashCode和equals方法,比较的是地址值。因为Object的equals方法中使用是" == " 。
如果重写hashCode和equals方法,则比较的重写后的规则。
2.代码演示
/** * 等号 == */ public class TestEq { public static void main(String[] args) { // 1 " == "比较的是值 // 1.1 基本数据类型:数值 int a = 1; int b = 1; System.out.println( a == b ); //true // 1.2 引用数据类型:地址值 Student s1 = new Student(); Student s2 = s1; System.out.println( s1 == s2 ); //true Student s3 = new Student(); System.out.println(s2 == s3); //false } }
/** * equals 默认 */ public class TestEq2 { public static void main(String[] args) { // 2 equals Student2 s1 = new Student2(); Student2 s2 = s1; Student2 s3 = new Student2(); // Object.equals方法,默认使用 == System.out.println( s1.equals(s2) ); //true System.out.println( s2.equals(s3) ); //false }
/** * 重写 hashcode 和 equals */ public class TestEq2 { public static void main(String[] args) { // 2 equals Student2 s1 = new Student2("jack"); // 空、"rose" Student2 s2 = s1; Student2 s3 = new Student2("jack"); // 空 // Object.equals方法,默认使用 == System.out.println( s1.equals(s2) ); //true System.out.println( s2.equals(s3) ); //true } } class Student2 { private String name; public Student2() { //无参构造 } public Student2(String name) { //有参构造 this.name = name; } //name如果相同返回true @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student2 student2 = (Student2) o; return name != null ? name.equals(student2.name) : student2.name == null; } @Override public int hashCode() { return name != null ? name.hashCode() : 0; } }
3.hashCode() 和 equals() 作用和区别?
作用:hashCode()方法和equals()方法的作用一样,对比两个对象是否相等
区别:
equals() 比较对象很多内容,比较全面,耗时较多,效率就比较低。绝对可靠。
equal()相等的两个对象,hashCode()肯定相等
hashCode() 只比较一个hash值,效率就比较高。不可靠。
hashCode()相等的两个对象他们的equal()不一定相等
比较原则:
首先,比较hashCode(),如果不相同,两个对象肯定不相同。
如果hashCode()相同,再比较equals
目的:既能大大提高了效率也保证了对比的绝对正确性