答案是:==比较值或内存地址,equals()比较逻辑内容,重写equals()需遵守五契约并同步重写hashCode()。

==
int
char
boolean
==
equals()
Object
equals()
==
String
Integer
说实话,每次讲到
==
equals()
咱们先从最直观的看。如果你有两个
int
a = 5
b = 5
a == b
true
==
但如果换成对象呢?假设我们有
String s1 = new String("hello")String s2 = new String("hello")s1 == s2
false
new String()
String
s1
s2
==
立即学习“Java免费学习笔记(深入)”;
这时候
equals()
String
s1.equals(s2)
true
String
equals()
再来个例子,如果你自己写一个
Person
name
age
equals()
new Person("Alice", 30) == new Person("Alice", 30)false
new Person("Alice", 30).equals(new Person("Alice", 30))false
equals()
==
equals()
name
age
Person
有时候,我会看到一些新手,甚至是老手,在比较
Integer
Integer i1 = 100; Integer i2 = 100;
i1 == i2
true
Integer i3 = 200; Integer i4 = 200;
i3 == i4
false
Integer
equals()
总结一下,
==
equals()
equals()
重写
equals()
equals()
HashMap
HashSet
最基础的,就是
equals()
equals()
null
x
x.equals(x)
true
x.equals(y)
true
y.equals(x)
true
ColorPoint
Point
ColorPoint
equals()
x, y
new Point(1,2).equals(new ColorPoint(1,2,Color.RED))
true
new ColorPoint(1,2,Color.RED).equals(new Point(1,2))
ColorPoint
color
false
equals()
x.equals(y)
true
y.equals(z)
true
x.equals(z)
true
x.equals(y)
equals()
null
x
x.equals(null)
false
NullPointerException
除了这五大契约,还有一个非常关键的点:重写 equals()
hashCode()
HashMap
HashSet
hashCode()
equals()
hashCode
HashMap
get()
hashCode()
equals()
equals()
hashCode()
所以,在实现
equals()
@Override
public boolean equals(Object o) {
if (this == o) return true; // 自反性,性能优化
if (o == null || getClass() != o.getClass()) return false; // 非空性,类型检查
// 或者用 o instanceof MyClass,但这在继承场景下可能带来对称性问题,getClass() 更严格
MyClass myClass = (MyClass) o;
// 逐一比较关键字段
return field1 == myClass.field1 &&
Objects.equals(field2, myClass.field2) && // 使用 Objects.equals 处理 null 值
// ... 其他字段
;
}
@Override
public int hashCode() {
// 使用 Objects.hash() 方便地生成哈希码,它能处理 null 值
return Objects.hash(field1, field2 /*, ... 其他字段 */);
}这里
Objects.equals()
Objects.hash()
null
if (field1 != null ? field1.equals(myClass.field1) : myClass.field1 == null)
String
Integer
equals()
HashMap
HashSet
String
Integer
equals()
以上就是Java中==和equals()方法的区别是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号