总结
Integer
是采用valueOf
方法进行装箱的,当取值在[-127,128]之间时,会进行对象复用。Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是类似的。Double、Float
的valueOf
方法的实现是类似的,这些方法没有进行对象复用。Boolean
的valueOf
方法如下:
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
public static final Boolean TRUE = new Boolean(true);
/**
* The Boolean object corresponding to the primitive
* value false.
*/
public static final Boolean FALSE = new Boolean(false);
复制代码
所以,只要相等,都是同一个对象。
练习题
public class Main {
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);
System.out.println(e==f);
System.out.println(c==(a+b));
System.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));
}
}
复制代码
答案:
true
false
true
true
true
false
true
复制代码