非常经典的一个面试题?先说清楚一个,再来说另一个?
==用来判断两个变量之间的的值是否相等。
变量就可以分为: 基本数据类型变量,引用类型。
1、基本数据类型的变量直接比较值
2、引用类型比较对应的引用指向的内存的首地址。
equals只有引用数据类型有这个方法,默认继承自Object类:
public boolean equals(Object obj) {
return (this == obj);
}
默认比较的是根据==比较的是地址值。
但是如果类重写了equals方法就要根据重写的方法来判断:
像String重写了equals比较的是字符串的内容是不是相等。
Integer类的缓存机制
我们查看Integer的源码,就会发现里面有个静态内部类。
该类的作用是将数值等于-128-127(默认)区间的Integer实例缓存到cache数组中。通过valueOf()方法很明显发现,当再次创建值在-128-127区间的Integer实例时,会复用缓存中的实例,也就是直接指向缓存中的Integer实例。注意,这里的创建不包括用new创建,new创建对象不会复用缓存实例。
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() {}
}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public static void main(String[] args) {
Integer a= 11;
Integer b =11;
System.out.println(a==b); // true情况一 Integer 直接赋值 都会自动装箱 整数类提供了缓存机制 在整数类加载时创建-128~127的对象缓存
Integer a1=128; //以后赋值 如果缓存有 会自动使用缓存中的对象。注意:仅适用于直接复制时候的自动装箱 不适用于new
Integer b1=128; // a 和 b 符合上述情况 都使用了缓存中的对象 两者的内存地址相同,指向一个对象 故最后相等.
System.out.println(a1==b1);//false 128不在-128~127之间的 自动装箱时缓存没找到 就是new 所以地址不一样 false
int a2 = 128;
System.out.println(a1==a2);//true情况二 : Integer 和 int 比较 Integer会自动拆箱 相当于比较 两个 int
Integer a3 = new Integer(1);//情况三 两个Integer对象 直接new Integer 创建的两个对象之间 比较 比地址 肯定为false
Integer b3 = new Integer(1);
System.out.println(a3 == b3); //false
}
情况一 Integer 直接赋值 都会自动装箱 整数类提供了缓存机制 在整数类加载时创建-128~127的对象缓存,以后赋值 如果缓存有 会自动使用缓存中的对象。
注意:仅适用于直接复制时候的自动装箱 不适用于new
a 和 b 符合上述情况 都使用了缓存中的对象 两者的内存地址相同,指向一个对象 故最后相等.
情况二 : Integer 和 int 比较 Integer会自动拆箱 相当于比较 两个 int
情况三 两个Integer对象 直接new Integer 创建的两个对象之间 比较 比地址 肯定为false
总结
- Byte、Short、Integer、Long、Character都是具有缓存机制的类。
缓存工作都是在静态块中完成,在类生命周期的初始化阶段执行。
2、缓存范围?
Byte,Short,Integer,Long为 -128 到 127。Character范围为 0 到 127
3、Integer可以通过jvm参数指定缓存范围,其它类都不行。
Integer的缓存上界high可以通过jvm参数-XX:AutoBoxCacheMax=size指定,取指定值与127的最大值并且不超过Integer表示范围,而下界low不能指定,只能为-128。