拆装箱易错面试题

一.包装类与基本数据类型比较

1 public class IntegerDemo {
2     public static void main(String[] args) {
3   
4         int i = 10;
5         Integer ii = 10;
6         System.out.println(i == ii);
7     }
8 }
9 输出结果:true

包装类在与基本类型在进行数值比较时:包装类会自动拆箱成对应的基本类型数据

如上代码在进行比较时,Integer类型的ii会拆箱成int类型的ii与i进行比较

二.ValueOf

 1 public class IntegerDemo {
 2     public static void main(String[] args) {
 3         
 4         Integer i1 = 100;
 5         Integer i2 = 100;
 6         Integer i3 = 200;
 7         Integer i4 = 200;
 8         System.out.println(i1 == i2);
 9         System.out.println(i3 == i4);
10     }
11 }
12 输出结果:
13 true
14 false

这些赋值实际上分为两步(以Integer i1 = 100为例):

  1.定义基本数据类型数据并赋值:int i = 100;

  2.将基本数据类型转换为包装类:Integer i1 = Integer.valueOf(i);

这是ValueOf方法中一个很小的知识点,即使工作了的同事也很容易翻车,需要我们从源代码中找答案

1 ValueOf()代码:
2  public static Integer valueOf(int i) {
3         if (i >= IntegerCache.low && i <= IntegerCache.high)
4             return IntegerCache.cache[i + (-IntegerCache.low)];
5         return new Integer(i);
6     }

我们发现在valueOf中传入的值会进行判断,那么这个判断的范围是什么呢?

static final int low = -128;
static final int high;

我们发现最小值是-128,而最大值没有进行判断,那么最大值是多少呢?

 1 static {
 2     // high value may be configured by property
 3     int h = 127;
 4     String integerCacheHighPropValue =
 5         sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
 6     if (integerCacheHighPropValue != null) {
 7         try {
 8             int i = parseInt(integerCacheHighPropValue);
 9             i = Math.max(i, 127);
10             // Maximum array size is Integer.MAX_VALUE
11             h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
12         } catch( NumberFormatException nfe) {
13             // If the property cannot be parsed into an int, ignore it.
14         }
15     }
16     high = h;
17     cache = new Integer[(high - low) + 1];
18     int j = low;
19     for(int k = 0; k < cache.length; k++)
20         cache[k] = new Integer(j++);
21     
22     // range [-128, 127] must be interned (JLS7 5.1.7)
23     assert IntegerCache.high >= 127;
24 }

我们在静态代码块中发现了high的值,high的值一般等于h的值为127

那么我们得到结论:

  1.当传入的值在-128~127之间时,会从cache数组中返回Integer对象

  2.当传入的值不在-128~127之间时,就会new Integer(i)

得出答案:

  i1与i2传入的值为100,在-128~127之间,返回 Integer 对象的地址引用是一样的,结果为true

  i3与i4传入的值为200,不在-128~127之间,需要new对象,地址肯定不相同,此时结果也就为false了

 

posted @ 2020-03-20 17:12  showMeTheCodes  阅读(291)  评论(0编辑  收藏  举报