日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

JDK源码解析 Integer类使用了享元模式

發(fā)布時(shí)間:2025/4/16 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JDK源码解析 Integer类使用了享元模式 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

JDK源碼解析

Integer類使用了享元模式。

我們先看下面的例子:

public class Demo {public static void main(String[] args) {Integer i1 = 127;Integer i2 = 127; ?System.out.println("i1和i2對(duì)象是否是同一個(gè)對(duì)象?" + (i1 == i2)); ?Integer i3 = 128;Integer i4 = 128; ?System.out.println("i3和i4對(duì)象是否是同一個(gè)對(duì)象?" + (i3 == i4));} }

運(yùn)行上面代碼,結(jié)果如下:

為什么第一個(gè)輸出語(yǔ)句輸出的是true,第二個(gè)輸出語(yǔ)句輸出的是false?

通過(guò)反編譯軟件進(jìn)行反編譯,代碼如下:

public class Demo {public static void main(String[] args) {Integer i1 = Integer.valueOf((int)127);Integer i2 Integer.valueOf((int)127);System.out.println((String)new StringBuilder().append((String)"i1\u548ci2\u5bf9\u8c61\u662f\u5426\u662f\u540c\u4e00\u4e2a\u5bf9\u8c61\uff1f").append((boolean)(i1 == i2)).toString());Integer i3 = Integer.valueOf((int)128);Integer i4 = Integer.valueOf((int)128);System.out.println((String)new StringBuilder().append((String)"i3\u548ci4\u5bf9\u8c61\u662f\u5426\u662f\u540c\u4e00\u4e2a\u5bf9\u8c61\uff1f").append((boolean)(i3 == i4)).toString());} }

上面代碼可以看到,直接給Integer類型的變量賦值基本數(shù)據(jù)類型數(shù)據(jù)的操作底層使用的是?valueOf()?,所以只需要看該方法即可

public final class Integer extends Number implements Comparable<Integer> {public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}private static class IntegerCache {static final int low = -128;static final int high;static final Integer cache[]; ?static {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_VALUEh = Math.min(i, Integer.MAX_VALUE - (-low) -1);} catch( NumberFormatException nfe) {}}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() {}} }

可以看到?Integer?默認(rèn)先創(chuàng)建并緩存?-128 ~ 127?之間數(shù)的?Integer?對(duì)象

當(dāng)調(diào)用?valueOf?時(shí)如果參數(shù)在?-128 ~ 127?之間則計(jì)算下標(biāo)并從緩存中返回,

否則創(chuàng)建一個(gè)新的?Integer?對(duì)象。

總結(jié)

以上是生活随笔為你收集整理的JDK源码解析 Integer类使用了享元模式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。