1,先来看==和equals的区别
==对于基本数据类型比较的是值,而对于引用类型比较的就是引用的地址,即两个引用是否指向同一个对象实例
- int a = 128;
- int b = 128;
- System.out.println(a==b);
- Integer c = 127;
- Integer d = 127;
- System.out.println(c==d);
- Integer e = 128;
- Integer f = 128;
- System.out.println(e==f);
-
- true
- true
- false
equals 对于没有重写equals方法的引用类型的比较和==是一样的,只是String,包装类等重写了equals方法,所以按重写后的规则进行比较,比较的是对象指向的内容是否相等;对于基本数据类型则没有equals方法
2,原因
查看Integer源码发现,Integer内部有一个静态变量缓存池IntegerCache,里面声明了一个Integer[]数组,范围-128——127
- 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() {}
- }
当我们声明Integer e = 128 ,其实就是调用Integer的valueOf(int i)方法进行自动装箱
- public static Integer valueOf(int i) {
- if (i >= IntegerCache.low && i <= IntegerCache.high)
- return IntegerCache.cache[i + (-IntegerCache.low)];
- return new Integer(i);
- }
如果范围不超过-128——127,则从IntegerCache中直接获取Integer对象,如果不在范围内则会new一个新的Integer对象。
根据==和equals区别可以得到为什么要用equals比较了。