System.out.println(Integer.valueOf("127")==Integer.valueOf("127")); --> **TRUE**
System.out.println(Integer.valueOf("128")==Integer.valueOf("128")); --> **FALSE**
原因是因爲Integer內部有緩存-128到127的小對象。
public static Integer valueOf(String string) throws NumberFormatException {
return valueOf(parseInt(string));
}
public static Integer valueOf(int i) {
return i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];
}
/**
* A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing
*/
private static final Integer[] SMALL_VALUES = new Integer[256];
static {
for (int i = -128; i < 128; i++) {
SMALL_VALUES[i + 128] = new Integer(i);
}
}