public class Test {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
System.out.print((o1 == o2) + " " + (o1.equals(o2)));
}
}
我在不同的答案中读到了这个:
The
==
operator tests whether two variables have the same references (aka pointer to a memory address).Whereas the
equals()
method tests whether two variables refer to objects that have the same state (values).
在这里,由于 o1
和 o2
引用了两个不同的对象,我明白为什么 ==
返回 false。
但这两个对象都是使用 Object
类的默认构造函数创建的,因此具有相同的值。为什么 equals()
方法返回 false?
最佳答案
执行equals()
由 java.lang.Object
提供定义返回 false
,除非引用引用同一个对象,在这种情况下它返回 true
.
这是设计使然(该方法模仿 ==
的行为)并鼓励程序员实现他们自己的 equals()
版本,如果合适的话,为他们的class
。例如,参见java.lang.String#equals
如果另一个 String
则比较内容作为参数传递。
关于java - 当两个对象相同时,为什么 equals() 方法返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43048899/