初学者对自动装箱和自动拆箱的认识(IntegerCache的缓存数组)

来源:互联网 发布:苏州迈科网络 编辑:程序博客网 时间:2024/05/16 05:23

自己对自动装箱和拆箱的一些认识,希望对大家有所帮助,不足和错误之处还望之处。


自动装箱,自动拆箱调用的方法:
自动装箱调用的方法: java源码如下:
private static class IntegerCache{        static final Integer cache[];        static{                 对-128到127对象的创建                 }}public static Integer  valueOf(int i){       if(i <= IntegerCache.high && i >= IntegerCache.low)              return IntegerCache.chache[i - IntegerCache.low];      return new Integer(i);}
Integer类中有个IntegerCache的静态内部类(类级内部类),里面对一些常用的int数字,准确的说是-128到127之间的数字进行Integer对象的创建,并放在一个静态缓存数组中(Integer cache[])。
Integer i = 100; 补全的实际代码为: Integer i = Integer.valueOf(100);由于100在缓存的数值范围内(-128——127)所以,并没有创建新的Integer对象,而是引用IntegerCache内部的Integer cache []数组中的对象(静态数据,该类对象所共有)。
Integer j = 200; 补全的实际代码为:Integer i = Integer.valueOf(100);但是其调用的确实new Integer(200);构造器进行对象创建。
举例:
  public static void main(String[] args) {                Integer a=100;                Integer b=100;                 Integer c=200;                Integer d=200;                System.out.println(a==b);   //1               System.out.println(a==100); //2                  System.out.println(c==d);   //3               System.out.println(c==200); //4       }  
结果是,true true false true
拆箱调用的是 java源码如下:
private final int value;public Integer(int value){    this.value = value;}public int  intValue(){   return value;}




阅读全文
0 0