给Integer类型赋值基本数据
给Integer类型赋值基本数据
01 运行下面代码,num3和num2是同一个对象,num4和num5不是同一个对象
public class IntegerTest { public static void main(String[] args) { Integer num1 = new Integer(127); Integer num2 = 127; Integer num3 = 127; Integer num4 = 128; Integer num5 = 128; System.out.println(num1==num2); //结果: false System.out.println(num3==num2); //结果: true System.out.println(num4==num5); //结果: false } }
02 通过反编译软件发现,直接给Integer类型赋值基本数据的底层操作使用的是valueOf()
public class IntegerTest { public static void main(String[] args) { Integer num1 = new Integer(127); Integer num2 = Integer.valueOf(127); Integer num3 = Integer.valueOf(127); Integer num4 = Integer.valueOf(128); Integer num5 = Integer.valueOf(128); System.out.println((num1 == num2)); System.out.println((num3 == num2)); System.out.println((num4 == num5)); } }
03 摘取关键源码
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 { // high value may be configured by property int h = 127; String integerCacheHighPropValue = 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() {} } }
Integer使用了享元模式,重复使用相同或像是的对象,节约系统资源