你看到这个标题是不是很惊讶!这不是结果都一样为false的吗
如果是下面代码:母庸质疑 都是new出来的对象 比较的是内存地址值 肯定不一样。
Integer a = new Integer(100);
Integer b = new Integer(100);
System.out.println(a==b);
如果是下面这几行代码:结果确实不是我们想的这样的
Integer a=100, b=100;
//结果为true
System.out.println(a==b);
Integer c=1000, d=1000;
//结果为false
System.out.println(c==d);
为什么结果不一样首先我们得知道java中自动装箱的概念.
什么是自动装箱
- 自动装箱就是自动将原始类型值转化为integer对象,比如说int 类型转换为integer对象。
因为这里的装箱不是人为转换的所以是自动装箱.
原始类型byte, short, char, int, long, float, double 和 boolean 对应的封装类为Byte, Short, Character, Integer, Long, Float, Double, Boolean。 - IntegerCache内部实现了一个Integer的静态常量数组,在类加载的时候,执行static静态块进行初始化-128到127之间的Integer对象,存放到cache数组中。cache属于常量,存放在java的方法区中。
//这行代码实际上自动装箱就会执行下面的代码
Integer a=100, b=100;
Integer b = Integer.valueOf(100);
其次就是在Integer类中有一个静态内部类IntegerCache,直接看源码
public static Integer valueOf(int i) {
//判断i是否在-128和127之间,存在则从IntegerCache中获取包装类的实例,否则new一个新实例
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[];
//静态方法,类加载的时候进行初始化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静态内部类中的代码块预先的对范围[-128—127]的值进行了实例化,这就是为什么第一个结果为true,第二个结果为false。
Integer a=100, b=100;
//结果为true
System.out.println(a==b);
Integer c=1000, d=1000;
//结果为false
System.out.println(c==d);
知道了这些我们对以下困惑就知道为什么了。
int i = 127;
int j = 128;
Integer a = 102;
Integer b = 102;
Integer c = 0;
Integer n = new Integer(102);
Integer n1 = new Integer(102);
//基本数据类型比较 值不相等为false
System.out.println(i==j);
//int值只要在-128和127之间的自动装箱对象都从缓存中获取的,所以为true
System.out.println(a==b);
//数值计算先进行拆箱转换为int类型比较数值 true
System.out.println(a==b+c);
//比较的内存地址值 false
System.out.println(n==n1);