如何使用IntegerIntegerCache

這篇文章主要介紹“如何使用Integer IntegerCache”,在日常操作中,相信很多人在如何使用Integer IntegerCache問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何使用Integer IntegerCache”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)!專注于網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、成都小程序開發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了涇川免費建站歡迎大家使用!

 Integer s = 1;
 Integer s1 = 1;;
 System.out.println(s == s1);

 Integer s2 = 128;
 Integer s3 = 128;
 System.out.println(s2 == s3);

問題由此展開,會打印出true, false; 第二個是我們正常理解的答案。再理解為什么第一個打印是true,先了解下 == 和 equals

== :

基本類型一般都用 == ,比較的是內(nèi)存地址,如果內(nèi)存地址是一樣的那么兩個值自然也是相等的。

equals:

對象的比較一般都用equals, equals比較的是對象的內(nèi)容

所以

Integer s = 1;
Integer s1 = 1;;
System.out.println(s.equals(s1)); // true

我們再回來看看開頭的問題,關(guān)鍵在于Integer中內(nèi)部類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;
            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;
        }

        private IntegerCache() {}
    }

-128 - 127范圍的數(shù)字都放在了cache數(shù)組中,所以再找個范圍內(nèi) == 比較都是true.

那么好處是直接在緩存中去取肯定要比生成一個對象要好太多啊

Byte Short Long 這幾個都有類似的做法

到此,關(guān)于“如何使用Integer IntegerCache”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

網(wǎng)頁標(biāo)題:如何使用IntegerIntegerCache
當(dāng)前地址:http://muchs.cn/article6/johhig.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)關(guān)鍵詞優(yōu)化、軟件開發(fā)、品牌網(wǎng)站制作、做網(wǎng)站移動網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

營銷型網(wǎng)站建設(shè)