• 一个关于Integer的秘密


    版权声明:本文为博主原创文章,未经博主同意不得转载。 https://blog.csdn.net/xiaoduishenghuogo/article/details/27058481

    先让大家看一段简单的代码:

    public static voidmain(String[] args) {
    Integera = 1;
    Integerb = 1;
     
    Integerc = 222;
    Integerd = 222;
     
    System.out.println(a== b);
    System.out.println(c== d);
    }

    大家猜一下。输出的结果会是什么?我想大多数刚開始学习的人都会觉得是:true  true

    但是,实际呢?正确答案是:true

    false。这时,是不是有人開始纳闷了,不禁问道:为什么呢?逻辑都一样,仅仅是数字不同,难道跟数字有关?恭喜你。答对了,确实跟数字有关。以下我就带大家看看当中的缘由。

     

    我们看一下integer源代码中的两个方法:

    publicstatic Integer valueOf(int i) {
            if(i >= -128 && i <=IntegerCache.high)
                return IntegerCache.cache[i + 128];
            else
                return new Integer(i);
        }
     
    privatestatic class IntegerCache {
            static final int high;
            static final Integer cache[];
     
            static {
                final int low = -128;
     
                // high value may be configured byproperty
                int h = 127;
                if (integerCacheHighPropValue !=null) {
                    // Use Long.decode here toavoid invoking methods that
                    // require Integer's autoboxingcache to be initialized
                    int i =Long.decode(integerCacheHighPropValue).intValue();
                    i = Math.max(i, 127);
                    // Maximum array size isInteger.MAX_VALUE
                    h = Math.min(i,Integer.MAX_VALUE - -low);
                }
                high = h;
     
                cache = new Integer[(high - low) +1];
                int j = low;
                for(int k = 0; k < cache.length;k++)
                    cache[k] = new Integer(j++);
            }
     
            private IntegerCache() {}
        }

    当我们初始化一个integer类型的变量时。如:Integer a = 1。实际上它调用了integer中的valueOf方法,相当于Integera = Integer.valueOf(1),而在这种方法内部有一个缓存的机制。

    它会推断你给变量赋的值是否在-128——127之间。假设是,那么它直接从缓存里去取对象。反之才会新创建一个对象。

    也就是说,当程序运行Integerb = 1时。缓存中已经存在这个integer对象,它直接将b指向缓存中的对象,结果就是ab指向同一对象,而cd就不同了。它们两个终于会指向两个新创建的不同的对象,运行c==d时。自然不会相等。如今大家该明确了吧。

     

    明确了这个原理,最重要的还是要应用于实际。当我们在程序中操作小整型数字的时候,我们要充分利用integer中的缓存机制,节省程序创建对象的时间,以此来提高我们程序的效率。

     

    最后,假设有人关心==equal的差别,请看以下这篇文章:

    具体解释java中equals和== 的差别



     

  • 相关阅读:
    iptables关键学习总结
    iptables关键学习总结
    .net中操作Visual SourceSafe
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10567406.html
  • Copyright © 2020-2023  润新知