8大基本数据类型中,除了布尔类型和两个浮点类型以外,都提供了缓存机制,其内部有一个静态类XxxCache(IntegerCache、ShortCache、ByteCache、LongCache),这个静态内部类里维护了一个数组,把-128~127之间的值缓存起来(Character缓存了0~127)。
private static class CharacterCache { private CharacterCache(){} static final Character cache[] = new Character[127 + 1]; static { for (int i = 0; i < cache.length; i++) cache[i] = new Character((char)i); } }
当我们给定的数值在缓存的范围内,不会新建对象,直接从缓存里获取。
public static Character valueOf(char c) { if (c <= 127) { // must cache return CharacterCache.cache[(int)c]; } return new Character(c); }
所以 ,下面的面试题结果显而易见,i1、i2和i5都是调用valueOf()方法来创建对象,这时候会先判断数字127在不在给定范围-128~127内,如果在,返回数值中指定位置的元素。因为i1、i2和i5都是获取到缓存数组同一位置的元素,他们的引用肯定相等。
public static void main(String[] args) {
Integer i1 = Integer.valueOf(127);
Integer i2 = Integer.valueOf(127);
Integer i3 = new Integer(127);
Integer i4 = new Integer(127);
Integer i5 = 127;
System.out.println(i1 == i2);
System.out.println(i1 == i3);
System.out.println(i3 == i4);
System.out.println(i3 == i5);
System.out.println(i1 == i5);
}
运行之后,结果并没有让人意外:
true
false
false
false
true