我正在做以下比较:
atividade.getEscala().getId() == escala.getId()
Run Code Online (Sandbox Code Playgroud)
它会返回,false但如果我输入atividade.getEscala().getId().intValue() == escala.getId().intValue()则返回true.true我写的时候也会回来atividade.getEscala().getId().toString().equals(escala.getId().toString())
我知道通过调试两个变量的内容是相同的((java.lang.Long) 2在显示视图中),那么为什么当我将long与just进行比较时它会返回false ==?
当您使用==两个引用时,您将比较引用是否相同,而不是引用的对象的内容是否相同.
使用自动装箱缓存使这变得更加复杂.例如,缓存介于-128和127之间的长度,这样您每次都会获得相同的对象.
例如
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
Run Code Online (Sandbox Code Playgroud)
由于存在溢出的风险,比较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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4856 次 |
| 最近记录: |