自动封箱和拆箱
Integer 中
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
如果没有设置IntegerCache.high的值,默认为127,也就是说值在-128~127之间,返回的都是同一个对象。
-
Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;System.out.println(f1 == f2);System.out.println(f3 == f4);
输出结果是:
truefalse
Long、Byte、Short同理。
Boolean中
public static Boolean valueOf(boolean b) { return (b ? TRUE : FALSE); }Character中
public static Character valueOf(char c) { if (c <= 127) { // must cache return CharacterCache.cache[(int)c]; } return new Character(c); }
Double中
-
public static Double valueOf(double d) {return new Double(d);}
对于任何的duoble类型的数据,每次都是从新装箱,生一个新的对象;Float类型同理。
-
public static void main(String[] args) {Integer a = 1;Integer b = 2;Integer c = 3;Integer d = 3;Integer e = 321;Integer f = 321;Long g = 3L;Long h = 2L;System.out.println(c==d);//不用解释了把,关于Integer中写的很清楚-128~127都是自动装箱成同一个对象了System.out.println(e==f);//看Integer中解释System.out.println(c==(a+b));//因为+所有a和b自动拆箱,会各自调用IntValue()方法,得到值后会在调用Integer.valueOfSystem.out.println(c.equals(a+b));System.out.println(g==(a+b));System.out.println(g.equals(a+b));System.out.println(g.equals(a+h));//因h是long类型,a则自动向上转型为Long}
输出结果:
truefalsetruetruetruefalsetrue- true

浙公网安备 33010602011771号