Java自动装箱规则 [英] Java autoboxing rules

查看:150
本文介绍了Java自动装箱规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名java新手,并且对以下示例感到困惑。是否可以认为==符号将比较整数和autoboxed Integers之间的值,并比较整数之间的参考地址?

I am a java novice and so confused by the following example. Is it okay to think that "==" sign will compare the values between Integers and "autoboxed" Integers from int, and compare reference address between Integers?

那么双打和0/0怎么样?

What about doubles and 0/0?

import edu.princeton.cs.introcs.*;

public class Autoboxing {

    public static void cmp(Integer first, Integer second) {
        if (first < second)
            StdOut.printf("%d < %d\n", first, second);
        else if (first == second)
            StdOut.printf("%d == %d\n", first, second);
        else if (first > second)
            StdOut.printf("%d > %d\n", first, second);
        else
            StdOut.printf("%d and %d are incomparable\n", first, second);
    }

    public static void main(String[] args) {
        cmp(new Integer(42), 43);
        cmp(new Integer(42), new Integer(42));
        cmp(43, 43);
        cmp(142, 142);

        Integer a0 = 1000;
        int b0 = 1000;
        Integer c0 = 1000;
        StdOut.println("a0==b0?" + (a0==b0));
        StdOut.println("a0==c0?" + (a0==c0));
        StdOut.println("b0==c0?" + (b0==c0));

        double x1 = 0.0, y1 = -0.0;
        Double a1 = x1, b1 = y1;
        StdOut.println(x1 == y1);
        StdOut.println(a1.equals(b1));

        double x2 = 0.0/0.0, y2 = 0.0/0.0;
        Double a2 = x2, b2 = y2;
        StdOut.println(x2 != y2);
        StdOut.println(!a2.equals(b2));
    }

}

结果是:

42 < 43
42 and 42 are incomparable
43 == 43
142 and 142 are incomparable
=====
a0==b0?true
a0==c0?false
b0==c0?true
=====
true
false
=====
true
false


推荐答案

<$> <$> <$> c $ c>算术运算符,比较运算符出现。

例如:

Integer a = 10;
a = a+10; //1.unboxing a to int 2.calculate a+10 3.boxing 20 to Integer.
System.out.print(a > 10); //1.unboxing a to int 2. compare

但是当 == 出现,取决于。

如果拳击类型出现在双方,它将会比较参考。但如果基本类型出现在一边,另一边是拳击类型,拳击类型将取消装箱到基本类型。

If boxing type appear on both side, it will compare the reference.But if base type appear on one side, and the other side is a boxing type, the boxing type will unboxing to base type.

例如:

Integer a = new Integer(129);
Integer b = new Integer(129);
System.out.println(a == b); // compare reference return false
System.out.println(a == 129); // a will unboxing and compare 129 == 129 return true

PS:In Java.lang.Integer 根据JLS的要求,缓存以支持-128和127(包括)之间的值的自动装箱的对象标识语义。
查看源代码

PS: In Java.lang.Integer Cache to support the object identity semantics of autoboxing for values between -128 and 127 (inclusive) as required by JLS. See source code

所以:

Integer a = 127;
Integer b = 127; //cached, the same as b a==b return ture

Integer c = 129;
Integer d = 129; // not cached, c==d return false

这篇关于Java自动装箱规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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