现在的位置: 首页 > 综合 > 正文

java拆箱 装箱

2018年06月30日 ⁄ 综合 ⁄ 共 1131字 ⁄ 字号 评论关闭

装箱就是把值类型转变为引用类型 Integer i = 10;

拆箱就是把引用类型转变为值类型 int i = new Integer(10);

  1. /**  
  2.  * ==号是比较两个基本类型是否相等,或者比较两个对象引用是否相同  
  3. */  
  4.  public class T {   
  5.     
  6.      public static void main(String[] args) {   
  7.          Integer i1 = 128;   
  8.          Integer i2 = 128;   
  9.          int i3 = 128;   
  10.          int i4 = 128;   
  11.          Integer i5 = 127;   
  12.          Integer i6 = 127;   
  13.             
  14.          Long long1 = 128L;   
  15.          Long long2 = 128L;   
  16.          long long3 = 128L;   
  17.          long long4 = 128L;   
  18.         long long5 = -128L;   
  19.          long long6 = -128L;   
  20.             
  21.         //-128 ~ 127之间数值装箱时会共享内存副本, 超过这个范围,则不会共享引用,即对象地址将不同   
  22.             
  23.          System.out.println(i1 == i2); //实质是比较两个不同引用 false   
  24.         System.out.println(i5 == i6); //实质是比较两个相同(共享)引用true   
  25.         System.out.println(i1 == i3); //先将i1拆箱,然后比较基本类型 true   
  26.         System.out.println(i1.equals(i4)); //先将i4装箱,然后比较基本类型 true   
  27.            
  28.         System.out.println(long1 == long2);//两个引用不同 false   
  29.         System.out.println(long5 == long6);//共用副本 true   
  30.         System.out.println(long1 == long3);//long1先拆箱, 在比较 true   
  31.          System.out.println(long2.equals(long4));//long4先装箱, 再equals, true   
  32.      }   
  33.  }  

抱歉!评论已关闭.