加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么返回false和true?

发布时间:2020-12-15 00:04:55 所属栏目:Java 来源:网络整理
导读:public class Test { public static final Double DEFAULT_DOUBLE = 12.0; public static final Long DEFAULT_LONG = 1L; public static Double convertToDouble(Object o) { return (o instanceof Number) ? ((Number) o).doubleValue() : DEFAULT_DOUBLE;
public class Test {
    public static final Double DEFAULT_DOUBLE = 12.0;
    public static final Long DEFAULT_LONG = 1L;

    public static Double convertToDouble(Object o) {
        return (o instanceof Number) ? ((Number) o).doubleValue()
                : DEFAULT_DOUBLE;
    }

    public static Long convertToLong(Object o) {
        return (o instanceof Number) ? ((Number) o).longValue() : DEFAULT_LONG;
    }

    public static void main(String[] args){
        System.out.println(convertToDouble(null) == DEFAULT_DOUBLE);
        System.out.println(convertToLong(null) == DEFAULT_LONG);
    }
}

解决方法

编辑

三元运算符执行some type conversions under the hood.在您的情况下,您混合基元和包装类型,在这种情况下包装类型被取消装箱,然后三元运算符的结果被“重新装箱”:

If one of the second and third operands is of primitive type T,and the type of the other is the result of applying boxing conversion (§5.1.7) to T,then the type of the conditional expression is T.

所以你的代码基本上等同于(除了longValue应该是doubleValue的错误):

public static void main(String[] args){
    Double d = 12.0;
    System.out.println(d == DEFAULT_DOUBLE);

    Long l = 1L;
    System.out.println(l == DEFAULT_LONG);
}

可以在某些JVM上缓存长值,因此==比较可以返回true.如果您使用equals进行了所有比较,那么在这两种情况下都会得到真实的结果.

注意,如果你使用public static final Long DEFAULT_LONG = 128L;并尝试:

Long l = 128L;
System.out.println(l == DEFAULT_LONG);

它可能会打印为false,因为Long值通常仅在-128和127之间缓存.

注意:JLS要求缓存-127和128之间的char,byte和int值,但不要说长的任何内容.因此,您的代码实际上可能会在不同的JVM上打印两次false.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读