java Long数据类型比较 [英] java Long datatype comparison

查看:771
本文介绍了java Long数据类型比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码为 long3 == long2 比较返回 false ,即使是字面值。

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));
    }
}


推荐答案

code> Long 是一个对象,而不是一个原始。使用 == 即可比较参考值

Long is an object, not a primitive. By using == you're comparing the reference values.

do:

if(str.equals(str2))

与您在第二次比较时一样。

As you do in your second comparison.

编辑 ..你认为其他对象的行为像 String 文字。他们不*。即使这样,你也不想使用 == String

I get it ... you are thinking that other objects act like String literals. They don't*. And even then, you never want to use == with String literals either.

(* Autobox类型实现flyweight模式,但只有值-128 - > 127.如果你 Long 等于 50 你确实有两个对同一个flyweight对象的引用,再次,从不使用== 来比较它们。

(*Autobox types do implement the flyweight pattern, but only for values -128 -> 127. If you made your Long equal to 50 you would indeed have two references to the same flyweight object. And again, never use == to compare them. )

要添加的修改:这是在Java语言规范中明确说明的,第5.1.7节

Edit to add: This is specifically stated in the Java Language Specification, Section 5.1.7:


如果被加框的值为true,false,一个字节或一个在\\\到\\\范围内的字符,或-128到127之间的一个int或短数字,那么let r1和r2是任何两个拳击转换的结果。 r1 == r2总是这样的。

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

注意 long 特别提到,但是当前的Oracle和OpenJDK实现这样做(1.6和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 ==

Long l = 5L;
Long l2 = 5L;
System.out.println(l == l2);
l = 5000L;
l2 = 5000L;
System.out.println(l == l2);

输出:


true

false

true
false

这篇关于java Long数据类型比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆