Integer和int使用==比较的总结

System.out.println("_____________________________");

Integer a = new Integer(3);

Integer b = 3;

int c = 3;

System.out.println(a == b); //false

System.out.println(a == c); //true

Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;

System.out.println(f1 == f2); //true

System.out.println(f3 == f4); //false

System.out.println("_____________________________");

Integer i6 = 128;

Integer i7 = 128;

int i8 = 128;

System.out.println(i6 == i7); //false

System.out.println(i6 == i8); //true

Integer i = Integer.valueOf(128);//原理

System.out.println("_______________");

Integer i9 = 12;

Integer i11 = 12;

System.out.println(i9 == i11); //true

//输出结果

_____________________________

false

true

true

false

_____________________________

false

true

_______________

true

结果分析

21c8afb0edd271c839147a874dab64fa.png

Integer的自动拆箱会有一个过渡,此原理就是利用Integer.valueOf( )

如果当前数值在 -128到127之间那么根据以上图的原理,则必定为真true。

因为在范围内,它就会将这个int值存入到缓存数组中,后面每次都会先去数组中找这个值,找到了就true,找不到就false。

如果当前数字值不在此范围内,那么这个方法就会new Integer(i) 并将其值返回。

i6,i7是两个引用类型的,超出了范围就是直接new Integer(i),那么就是两个引用类型值进行比较地址值,结果false。

i6,i8是integer ,int --- i6会进行拆箱成为int,那么就是两个int类型的数值进行比较,则为true。

其余结果类似

缓存数组的源码

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() {}

}

28e55d8b4d824cc709ca8146ab16fe31.png

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐