Integer的拆箱装箱

xiaoxiao2021-02-28  136

基础类型和其对应的包装类

  - boolean(未定),char(2字节),byte(1字节),short(2字节),int(4字节),long(8字节),float(4字节),double(8字节)   - 包装类型:Boolean,Character,Byte,Short,Integer,Long,Float,Double

装箱和拆箱

装箱:自动根据数值创建对应的Integer对象,如:Integer i=10;

拆箱:自动将包装器类型转换成基本数据类型,如:Integer i=10;int n=i; Integer与int的区别最基本的是:Ingeter是int的包装类,int的初值为0,Ingeter的初值为null

原理:

反编译class文件:在装箱时自动调用了 Integer.valueOf (int x) 方法;在拆箱时自动调用  Integer.intValue() 方法

 

面试题目:

(1)下列代码输出什么

public static void main(String[] args) { Integer i1 = 127; Integer i2 = 127; Integer i3 = 200; Integer i4 = 200; System.out.println(i1==i2);// true System.out.println(i3==i4);// false }

这里i1和i2是同一对象,但i3和i4不是,首先要看valueOf 方法:

valueOf创建Integer对象时,如果数值在 [-128,127] 之间变返回IntegerCache.cache 中已经存在的对象的引用,否则创建一个新的对象。

// Integer的valueOf方法 public static Integer valueOf(int i) { if(i >= -128 && i <= IntegerCache.high) return IntegerCache.cache[i + 128]; else return new Integer(i); } //IntegerCache类 private static class IntegerCache { static final int high; static final Integer cache[]; static { final int low = -128; // high value may be configured by property int h = 127; if (integerCacheHighPropValue != null) { // Use Long.decode here to avoid invoking methods that // require Integer's autoboxing cache to be initialized int i = Long.decode(integerCacheHighPropValue).intValue(); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - -low); } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); } private IntegerCache() {} }

(2)Double类输出

两种都是false,Double类的 valueOf 和 Integer 的实现方式是不一样的,原因是在某个范围内的整数数值的个数时有限的,而浮点数却不是。

Integer,Short,Byte,Character,Long  这几个类的 valueOf 方法是类似的;Double,Float 的 valueOf 方法的实现是类似的 public static void main(String[] args) { Double i1 = 100.0; Double i2 = 100.0; Double i3 = 200.0; Double i4 = 200.0; System.out.println(i1==i2);//false System.out.println(i3==i4);// false }

(3)Integer i = new Integer(1) 和 Integer i = 1 

  1)第一种方式不会触发自动装箱的过程;而第二种方式会触发;

  2)在执行效率和资源占用上的区别。第二种方式的执行效率和资源占用在一般性情况下要优于第一种情况(不是绝对的)。

   

转载请注明原文地址: https://www.6miu.com/read-49044.html

最新回复(0)