Java中equals()方法的行为 [英] The behaviour of equals() method in Java
问题描述
考虑以下Java代码:
Consider the following Java code:
Object a = new Integer(2);
Object b = new Integer(2);
System.out.println(a.equals(b));
Object x = new Object();
Object y = new Object();
System.out.println(x.equals(y));
第一个打印语句打印 true
和第二个 false
。
The first print statement prints true
and the second false
.
如果这是故意的行为,这有助于用Java编程吗?
If this is an intentional behavior, how this helps programming in Java?
如果这不是故意行为,这是Java中的缺陷吗?
If this is not an intentional behavior, is this a defect in Java?
推荐答案
我将以保留方式回答您的问题,但如果问题的目的是让您学习并且您的解决方案是问StackOverflow,您应该知道自己在伤害自己。除此之外......
I'm going to answer your question with reservations, but you should know that you are hurting yourself if the intent of the question was to get you to learn and your solution was to ask StackOverflow. That aside...
此行为是故意的。
默认等于( )
上的方法java.lang.Object
比较内存地址,这意味着所有对象彼此不同(只有两个对同一对象的引用将返回 true
)。
The default equals()
method on java.lang.Object
compares memory addresses, which means that all objects are different from each other (only two references to the same object will return true
).
java.lang。整数
会覆盖它以比较 Integer
的值,因此两个不同的 Integer
s表示数字2比较相等。如果您使用 ==
,则两种情况都会得到 false
。
java.lang.Integer
overrides this to compare the value of the Integer
s, so two different Integer
s both representing the number two compare equal. If you used ==
instead, you would get false
for both cases.
Java中的标准做法是覆盖等于
方法,以便为具有以下内容的对象返回 true
相同的逻辑值,即使它们是在不同时间创建的(甚至是不同的参数)。如果你没有办法提问,那么让对象代表数字并不是很有用,这两个东西代表相同的值吗?。
Standard practice in Java is to override the equals
method to return true
for objects which have the same logical value, even if they were created at different times (or even with different parameters). It's not very useful to have objects representing numbers if you don't have a way to ask, "do these two things represent the same value?".
顺便提一下,这是一个切线,Java实际上为小值保留了 Integer
对象的缓存。所以有时你可能得到两个 Integer
对象,即使 ==
运算符也会返回 true
,尽管你从两个不同的来源获得它们。您甚至可以获得对于较大整数而言行为与对较小整数不同的代码,而不必查看整数值!
Incidentally, and this is a tangent here, Java actually keeps a cache of Integer
objects for small values. So sometimes you may get two Integer
objects where even the ==
operator will return true
, despite you getting them from two different sources. You can even get code that behaves differently for larger integers than it does for smaller, without having it look at the integral values!
这篇关于Java中equals()方法的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!