美文网首页Java 小细节
Java Interger比较要用`equals`不能用`==`

Java Interger比较要用`equals`不能用`==`

作者: 谢随安 | 来源:发表于2017-09-26 11:28 被阅读83次

学习来源:知乎专栏《Java那些事儿》

执行如下代码:

public class IntegerCmp {
    public static void main(String[] args) {
        Integer i1 = 50;
        Integer i2 = 50;

        Integer i3 = 500;
        Integer i4 = 500;

        System.out.println("Using `==`:");
        System.out.println("i1 == i2:" + (i1 == i2));
        System.out.println("i3 == i4:" + (i3 == i4));

        System.out.println("Using `equals`:");
        System.out.println("i1.equals(i2):"+ i1.equals(i2));
        System.out.println("i3.equals(i4):"+ i3.equals(i4));
    }
}

相当简单,但是执行结果却有点让人摸不着头脑:

Using `==`:
i1 == i2:true
i3 == i4:false
Using `equals`:
i1.equals(i2):true
i3.equals(i4):true

equals的结果在意料之内,但是==的结果为什么却一个是true一个是false呢?

如果反编译.class文件,可以发现编译器在编译代码时,在声明的变量加上了valueOf方法,代码变成了如下的样子:

public class IntegerCmp {
    public IntegerCmp() {
    }

    public static void main(String[] args) {
        Integer i1 = Integer.valueOf(50);
        Integer i2 = Integer.valueOf(50);
        Integer i3 = Integer.valueOf(500);
        Integer i4 = Integer.valueOf(500);

        System.out.println("Using `==`:");
        System.out.println("i1 == i2:" + (i1 == i2));
        System.out.println("i3 == i4:" + (i3 == i4));
        System.out.println("Using `equals`:");
        System.out.println("i1.equals(i2):" + i1.equals(i2));
        System.out.println("i3.equals(i4):" + i3.equals(i4));
    }
}

以下是valueOf方法的实现:

    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

发现Integer的作者写这个类时,为了避免重复创建对象,对Integer的值做了缓存,如果值在缓存范围内(IntegerCache.low ~ IntegerCache.high),则直接返回缓存好的IntegerCache对象,否则new一个新的Integer对象返回。

查看IntegerCache中缓存的内容:

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            //加载JVM配置
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            //如果有值,就用配置的值初始化缓存数组
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;
            //否则缓存-128到127之间的整数值
            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

这是一个内部静态类,该类只能在Integer这个类的内部访问,这个类在初始化的时候加载JVM配置java.lang.Integer.IntegerCache.high,如果有值,就用配置的值初始化缓存数组,否则就缓存-128到127之间的整数值。

现在看之前的程序代码:

public class IntegerCmp {
    public static void main(String[] args) {
        Integer i1 = 50;
        Integer i2 = 50;

        Integer i3 = 500;
        Integer i4 = 500;

        System.out.println("Using `==`:");
        System.out.println("i1 == i2:" + (i1 == i2));
        System.out.println("i3 == i4:" + (i3 == i4));

        System.out.println("Using `equals`:");
        System.out.println("i1.equals(i2):"+ i1.equals(i2));
        System.out.println("i3.equals(i4):"+ i3.equals(i4));
    }
}

因为i1和i2的值为50,在-128到127之间,所以i1和i2指向的是同一缓存对象,因此i1 == i2返回true。
由于i3和i4的值不在缓存范围内,因此会new两个新的对象,因此i3==i4返回false。
关于equals的使用,见之后的文章。

结论:在比较两个Integer对象的值时(划重点:值),无论如何声明,都要使用equals去比较,不能使用==,Java中没有重载操作符的说法。

相关文章

网友评论

    本文标题:Java Interger比较要用`equals`不能用`==`

    本文链接:https://www.haomeiwen.com/subject/qetsextx.html