我正在进行以下比较:
atividade.getEscala().getId() == escala.getId()
并返回false
,但如果我输入atividade.getEscala().getId().intValue() == escala.getId().intValue()
,则返回true
。当我写true
atividade.getEscala().getId().toString().equals(escala.getId().toString())
我通过调试知道两个变量的内容是相同的(显示视图中为(java.lang.Long) 2
),那么为什么当我将长数与==
进行比较时它会返回false?
答案 0 :(得分:8)
当您使用==
两个引用时,您将比较引用是否相同,而不是引用的对象的内容是否相同。
使用自动装箱缓存会使这变得更加复杂。例如缓存-128到127之间的长度,这样每次都可以获得相同的对象。
e.g。
Long x = 100, y = 100;
System.out.println(x == y); // true, references are the same.
Long a = 200, b = 200; // values not cached.
System.out.println(a == b); // false, references are not the same.
System.out.println(a.equals(b)); // true, the objects referenced are equal
由于存在溢出风险,比较intValue()是危险的。
Long c = -1, d = Long.MAX_VALUE;
System.out.println(c.equals(d)); // false
System.out.println(c.longValue() == d.longValue()); // false
System.out.println(c.intValue() == d.intValue()); // true, lower 32-bits are the same.
答案 1 :(得分:1)
在对象上使用==运算符时,可以比较内存引用值,而不是值。对于基元,您可以比较值。
答案 2 :(得分:1)
如果两个值都是Long,则需要将它们与equals()进行比较,就像对所有引用类型一样。通过调用intValue(),您可以比较int primatives,其中==按照您的预期工作。
答案 3 :(得分:1)
==
运算符比较标识,而不是相等。为了平等,请使用equals()
。