equals ==(不求甚解 )补充 十七

/**
 * 总之: 
“==”比较的是值【变量(栈)内存中存放的对象的(堆)内存地址】 
基本数据类型比较:自然数值。

 引用:比较的也是值,只不过不是数值,是变量本身的值(这个值是内存地址)

        equals,类型 、值,相同,就返回 true

其实有疑惑,可以用 javap -c  EqualsTest2   (反编译class,class文件存放位置在bin目录里),

可以看到底层调用的函数

 *
 */
public class EqualsTest2 {
public static void main(String[] args) {
/**显然此处创建的对象和new 的对象用的方法是不一样的。所谓的装箱调用的是valuof()方法
IntegerCache [-128,127]
public static Integer valueOf(int i) {
       if (i >= IntegerCache.low && i <= IntegerCache.high)
           return IntegerCache.cache[i + (-IntegerCache.low)];
       return new Integer(i);
   }
**/
   Integer i=1;//装箱相当于调用Integer.valueOf(1)
   Integer j=1;
   
   System.out.println("i==1:"+(i==1));  //拆箱调用 Integer.intValue();
   System.out.println("(i==j):"+(i==j));
   System.out.println("===========================");
   
   Integer i2=128;      //装箱相当于调用Integer.valueOf(),128不在[-128,127],创建新对象
   Integer j2=128;
   System.out.println("i2==j2:"+(i2==j2));  //2个对象,肯定是2个不同的内存地址
   
   System.out.println("===========================");
   Integer i1=new Integer(1);
   Integer j1=new Integer(1);
   System.out.println("i1==j1:"+(i1==j1));
   
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章