Java中的equals()方法在Long数据类型上意外地工作 [英] The equals() method in Java works unexpectedly on Long data type
问题描述
让我们首先考虑Java中的以下表达式。
Let's first consider the following expressions in Java.
Integer temp = new Integer(1);
System.out.println(temp.equals(1));
if(temp.equals(1))
{
System.out.println("The if block executed.");
}
这些所有陈述都可以正常使用。毫无疑问。表达式 temp.equals(1)
按预期计算为 true
,并且<$ c $中的唯一语句c>如果块因此被执行。
These all statements work just fine. There is no question about it. The expression temp.equals(1)
is evaluated to true
as expected and the only statement within the if
block is executed consequently.
现在,当我更改数据类型时整数
到长
,语句 temp1.equals(1)
意外地评估为 false
,如下所示。
Now, when I change the data type from Integer
to Long
, the statement temp1.equals(1)
is unexpectedly evaluated to false
as follows.
Long temp1 = new Long(1);
System.out.println(temp1.equals(1));
if(temp1.equals(1))
{
System.out.println("The if block executed.");
}
这些是与前面代码段中提到的数据类型相同的语句已被改变,他们的行为正好相反。
These are the equivalent statements to those mentioned in the preceding snippet just the data type has been changed and they behave exactly opposite.
表达式 temp1.equals(1)
评估为 false
因此,中的唯一语句如果
块未执行,则与前面的语句相反。如何?
The expression temp1.equals(1)
is evaluated to false
and consequently, the only statement within the if
block is not executed which the reverse of the preceding statements. How?
推荐答案
您将 Long
与<$进行比较C $ C> INT 。 java.lang.Long #equals
表示等于
方法
将此对象与指定对象进行比较。当且仅当参数不为null并且是包含与此对象相同的long值的Long对象时,结果才为真。
Compares this object to the specified object. The result is true if and only if the argument is not null and is a Long object that contains the same long value as this object.
而是尝试 System.out.println(new Long(1).equals(1L));
现在您要比较 Long
到长
而不是长
到整数
,它将打印 true
。
Instead try System.out.println(new Long(1).equals(1L));
Now that you're comparing a Long
to a Long
instead of a Long
to an Integer
, it will print true
.
这篇关于Java中的equals()方法在Long数据类型上意外地工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!