java Long 数据类型比较
为什么下面的代码对于 long3 == long2 比较返回 false,即使它是字面量。
public class Strings {
public static void main(String[] args) {
Long long1 = 256L + 256L;
Long long2 = 512L;
Long long3 = 512L;
System.out.println(long3 == long2);
System.out.println(long1.equals(long2));
}
}
Why does the code below return false for long3 == long2 comparison even though it's literal.
public class Strings {
public static void main(String[] args) {
Long long1 = 256L + 256L;
Long long2 = 512L;
Long long3 = 512L;
System.out.println(long3 == long2);
System.out.println(long1.equals(long2));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这里 Long 是一个包装类,因此下面的行将比较引用而不是内容。
long3 == long2
与 ** .longValue() ** 进行比较总是更好,如下所示
long3.longValue() == long2.longValue()
如果我们使用-build equal() 方法也将通过空检查执行相同的操作。
long3.equals(long2)
下面是java中equals()的内部实现
Here Long is a Wrapper class so the below line will compare the reference not the content.
long3 == long2
its always better to compare with ** .longValue() ** like below
long3.longValue() == long2.longValue()
If we use in-build equal() method that also will do the same thing with null check.
long3.equals(long2)
Below is the internal implementation of equals() in java
Long
是一个对象,而不是基元。通过使用==
,您可以比较参考值。您需要这样做:
正如您在第二次比较中所做的那样。
编辑:我明白了...您认为其他对象的行为类似于
String
文字。他们不*。即便如此,您也永远不想将==
与String
文字一起使用。(*Autobox 类型确实实现了享元模式,但仅适用于值 -128 -> 127。如果您将
Long
等于50
,您确实会有两个对再次强调,永远不要使用 == 来比较它们)编辑添加:Java 语言规范中对此进行了明确规定,第 5.1.7 节:
请注意,没有特别提到
long
,但当前的 Oracle 和 OpenJDK 实现确实这样做了(1.6 和 1.7),这是从不的另一个原因使用==
输出:
Long
is an object, not a primitive. By using==
you're comparing the reference values.You need to do:
As you do in your second comparison.
Edit: I get it ... you are thinking that other objects act like
String
literals. They don't*. And even then, you never want to use==
withString
literals either.(*Autobox types do implement the flyweight pattern, but only for values -128 -> 127. If you made your
Long
equal to50
you would indeed have two references to the same flyweight object. And again, never use == to compare them. )Edit to add: This is specifically stated in the Java Language Specification, Section 5.1.7:
Note that
long
is not specifically mentioned but the current Oracle and OpenJDK implementations do so (1.6 and 1.7), which is yet another reason to never use==
Outputs:
您还可以使用以下方法从 Long 对象中获取原始值:
You could also get the primitive value out of the Long object using:
如果你想
这样做......
这符合你的目的并且速度更快,因为你正在比较两个基本类型值而不是对象。
If you want to do
do like this..
This serves your purpose and much faster because you are comparing two primitive type values not objects.