15 ==和equals的区别

vvEcho 2025-03-02 09:19:38
Categories: Tags:

1.==是一个操作符,eqauls是object类的方法
2.对于基本数据类型,==比较的是两个对象的值是否相等,对于引用数据类型,==比较的是两个对象的地址是否相等
3.equal比较的是对象的值是否相等

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class EqualityTest {
public static void main(String[] args) {
// 基本数据类型的比较
int x = 10;
int y = 10;
System.out.println("x == y: " + (x == y)); // 输出: true
System.out.println("x y equals " + (Objects.equals(x,y))); // 输出: true

int i = 128;
int j = 128;
System.out.println("\ni == j: " + (i == j)); // 输出:true
System.out.println("i j equals: " + (Objects.equals(i,j))); // 输出:true

Integer a1 = new Integer(33);
Integer b1 = new Integer(33);
System.out.println("\na1 == b1: " + (a1 == b1));// 输出false
System.out.println("a1 b1 equals: " + (a1.equals(b1)));// 输出true

// 考察int常量池范围 在这个范围里integer拆包指向的值都是常量池里的 -128~127
Integer a = 127;
Integer b = 127;
System.out.println("\na == b: " + (a == b));// 输出true
System.out.println("a b equals: " + (a.equals(b)));//输出true

// 超过168就new对象
Integer a2 = 128;
Integer b2 = 128;
System.out.println("\na2 == b2: " + (a2 == b2));// 输出false
System.out.println("a2 b2 equals: " + (a2.equals(b2))); //输出true

// 引用对象的比较
Integer a3 = new Integer(200);
Integer b3 = new Integer(200);
System.out.println("\na3 == b3: " + (a3 == b3));// 输出false
System.out.println("a3 b3 equals: " + (a3.equals(b3)));// 输出true

// ==比较的是两个存在于堆里不同的对象
String str1 = new String("test");
String str2 = new String("test");
System.out.println("\nstr1 == str2: " + (str1 == str2)); // 输出: false
System.out.println("str1 str2 equals " + (str1.equals(str2))); // 输出: true

// ==比较的是两个存在于常量池里相同的对象
String str3 = "ask";
String str4 = "ask";
System.out.println("\nstr3 == str4: " + (str3 == str4)); // 输出: true
System.out.println("str3 str4 equals: " + (str3.equals(str4))); // 输出: true

// ==比较的是常量池和堆里的两个不同的对象
String str5 = "java";
String str6 = new String("ja")+ new String("va");
System.out.println("\nstr5 == str6: " + (str5 == str6)); // 输出: false
System.out.println("str5 str6 equals: " + (str5.equals(str6))); // 输出: true

// 编译器会优化 str8直接会拼接成一个常量
String str7 = "python";
String str8 = "py" + "thon";
System.out.println("\nstr7 == str8: " + (str7 == str8)); // 输出: true
System.out.println("str7 str8 equals: " + (str7.equals(str8))); // true
}
}

为何要重写equals方法

因为equals方法比较的是对象的值是否相等,如果不重写默认的是Object类中的equals方法,而Object类中的equals方法比较的是两个对象的地址是否相等,所以如果两个对象值相等,但是地址不相等,那么equals方法会返回false

1
2
3
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}

为何要重写equals方法时必须重写hashcode方法?

规则1:若a.equals(b)为true,则a.hashCode()必须等于b.hashCode()。

规则2:若a.equals(b)为false,a.hashCode()与b.hashCode()可以相同(哈希冲突),但应尽量避免以提高性能。

若仅重写equals而不重写hashCode,可能破坏上述规则