The difference between == and equals
== The comparison is the value.
If the comparison is the basic data type, the comparison is the variable value.
If the comparison is the reference data type, the comparison is the address value
Equals compares the reference data type.
If the hashCode and equals methods are not overridden, the address value is compared. Because it is used in the equals method of Object.
If you override the hashCode and equals methods, compare the rewritten rules.
For example: when two String strings are compared: the content is compared. Because the bottom layer of String rewrites the equals method to compare content.
== number
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
}
}
@Data
class Student {
private String name;
}
equals default
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
}
}
class Student2 {
private String name;
}
Rewrite 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;
}
}
HashCode() and equals() function and difference
Function: The hashCode() method has the same function as the equals() method. It compares whether two objects are equal. The
difference:
- equals() compares objects with a lot of content, is more comprehensive, takes more time, and is less efficient. Absolutely reliable
equals() equals two objects, hashCode() must be equal - hashCode() only compares one hash value, the efficiency is higher, and
the two objects with equal hashCode() are not reliable, their equal() is not necessarily equal
Comparison principle:
compare first
- If hashCode() is not the same, the two objects are not the same
- If the hashCode() is the same, compare equals
Purpose: Not only can greatly improve the efficiency but also ensure the absolute correctness of the comparison