Java中的128陷阱

导读:本篇文章讲解 Java中的128陷阱,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

public class Test {
    public static void main(String[] args) {
        Integer a1=127;
        Integer a2=127;
        Integer b1=128;
        Integer b2=128;
        System.out.println(a1==a2);
        System.out.println(b1==b2);
    }
}

在这里插入图片描述

为什么第一个是true,而第二个却是false呢?

Java设计者认为:每次都要开辟新空间会占用大量的资源,因此他们规定在[-128,127] (因为Java设计者认为大家对数的使用大多在这个范围以内)之间的Integer类型的变量,直接指向常量池中的缓存地址,不会new开辟出新的空间,因此当值在[-128,127] 区间内的时候,两个相同值的变量会指向相同地址。

源码如下

/**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/71514.html

(0)
小半的头像小半

相关推荐

极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!