偶然在用==和equals的时候,涉及到了缓冲池这个概念,大概意思和Python里数据缓存一样的道理
public class Main { public static void main(String[] args) { Integer a1 = new Integer(1); Integer a2 = new Integer(1); System.out.println(a1 == a2); System.out.println(a1.equals(a2)); } }
首先来个简单的,==比较引用变量,为false;equals比较两个对象的值,都是1,为true
加一段就更能说明==的作用
public class Main { public static void main(String[] args) { Integer a1 = new Integer(1); Integer a2 = new Integer(1); System.out.println(a1 == a2); System.out.println(a1.equals(a2)); Integer a3 = new Integer(2); Integer a4 = a3; System.out.println(a3 == a4); System.out.println(a3.equals(a4)); } }
这里a4=a3赋值传递了引用,a3 == a4为true
下面继续加一段,才是要思考的
public class Main { public static void main(String[] args) { Integer a1 = new Integer(1); Integer a2 = new Integer(1); System.out.println(a1 == a2); System.out.println(a1.equals(a2)); Integer a3 = new Integer(2); Integer a4 = a3; System.out.println(a3 == a4); System.out.println(a3.equals(a4)); Integer a5 = 3; Integer a6 = 3; System.out.println(a5 == a6); System.out.println(a5.equals(a6)); } }
这里首先要清楚Integer是一个类,而不是byte,int这些基础类型,否则equals方法是无法调用的,编译肯定无法通过,在此基础上,理论上和第一段没有啥区别,==比较引用为false,equals为true,但实际的执行结果如下
false true true true true true
这里疑点就在a5 == a6上,首先自己的理解没有出错,其次会不会也出现了缓存和复用,可以写一个简单的测试程序
public class Main { public static void main(String[] args) { int min = 0; while (true) { Integer a1 = min; Integer a2 = min; if (a1 != a2) { ++min; System.out.print("[" + min + ", "); break; } --min; } int max = 0; while (true) { Integer a3 = max; Integer a4 = max; if (a3 != a4) { --max; System.out.println(max + "]"); break; } ++max; } } }
执行的结果是
[-128, 127]
从测试结果可以知道,Integer类型对于在这个区间里的整型数据是从缓冲池里面取的
详细来说就是:
假如没有通过new来创建新的Integer对象,指定对象的值在上面这个区间范围内,如果缓冲池里不存在该值的Integer对象,那么此时就会创建新的Integer对象,并存放在Integer缓冲池里
假如没有通过new来创建新的Integer对象,指定对象的值在上面这个区间范围内,如果缓冲池里已经存在该值的Integer对象,那么此时就不会创建新的Integer对象,而是直接从已有的Integer对象里取值,返回已存在的Integer对象的引用,因此上面值为3的对象已经存在于Integer缓冲池里,变量a5引用它,因为3在[-128,127]区间内,因此下面a6指向的值为3的对象并没有重新创建,而依旧是a5指向的对象,并且直接返回引用a5,也就是a6和a5其实是同一个引用,因此a5 == a6是true
其实这里可以看下源码,在Integer.java里的valueOf方法
/** * Returns an {@code Integer} instance representing the specified * {@code int} value. If a new {@code Integer} instance is not * required, this method should generally be used in preference to * the constructor {@link #Integer(int)}, as this method is likely * to yield significantly better space and time performance by * caching frequently requested values. * * This method will always cache values in the range -128 to 127, * inclusive, and may cache other values outside of this range. * * @param i an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since 1.5 */ public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
这里IntegerCache.low和IntegerCache.high的更新在下面一段,[-128,127]
/** * Cache to support the object identity semantics of autoboxing for values between * -128 and 127 (inclusive) as required by JLS. * * The cache is initialized on first usage. The size of the cache * may be controlled by the {@code -XX:AutoBoxCacheMax=} option. * During VM initialization, java.lang.Integer.IntegerCache.high property * may be set and saved in the private system properties in the * sun.misc.VM class. */ 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() {} }
直接看上面valueOf方法,传了一个整型参数,做了一下判断,如果在[-128,127]里,直接用基础数据,而如果不在这个范围以内,new了一个新的Integer对象,这就是上面为true的原因
其实除了Integer之外,String也有缓冲池,可以类似进行测试