搞清楚一道关于Integer的面试题
- 2019 年 10 月 7 日
- 筆記
public class IntegerDemo { public static void main(String[] args) { Integer a = 888; Integer b = 888; Integer c = 88; Integer d = 88; System.out.println(a == b); System.out.println(c == d); } }
上面这道题输出:
false true
因为Java的自动拆箱和自动封箱,那么
Integer a = 888;
就是相当于
Integer a = new Integer(888);
自然上面的变量a和b都是各自指向不同的对象引用地址。那么答案就肯定是false。
那为什么c===d就是指向同一个对象呢?
再来看看,Integer中部分源码
//具体源码部分 public static Integer valueOf(int i) { //i>=-128&&i<=127 if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); } //Integer的静态内部类 private static class IntegerCache { static final int low = -128; static final int high; //常量数组 static final Integer cache[]; static { // high value may be configured by property int h = 127 //省略无关代码.... high = h; //初始化cache数组大小 //cache的大小=127-(-128)+1=256 cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) //把-128到127的数字全部转换成Integer对象 //并存入到cache数组中。 cache[k] = new Integer(j++); } private IntegerCache() {} }
面试题2:
public class IntegerDemo { public static void main(String[] args) { Integer a = new Integer(88); test(a); System.out.println(a); } private void test(Integer integer){ integer=new Integer(99); } }
上面应该输出多少呢?
面试题3:
public class IntegerDemo { public static void main(String[] args) { Integer a = new Integer(88); a = 99; System.out.println(a); } }
这里又将输出多少呢?
继续看源码:
public final class Integer extends Number implements Comparable<Integer> { //final修饰变量,如果是基本数据类型的变量,则其数值一旦在初始化之后便不能更改 //如果是引用类型的变量,则在对其初始化之后便不能再让其指向另一个对象。 private final int value; public Integer(int value) { this.value = value; } }
面试题3中的a=99相当于a=new Integer(99);重新给把一个新的对象引用地址给了a,所以a变了,最后输出是99。
那么面试题2呢?
我们都知道在Java中,Java 只有值传递,只不过值传递分为:内存中数值的值传递以及内存地址数值的值传递,传递一个Integer变量参数进去,实际上是构建了一个副本,通过这个副本我们只能去修改原来Integer变量的非final成员变量(假如有的话,也可以是其他类型),上面也说了,如果去修改Integer类型的final变量,那么是会新new一个Integer变量,去覆盖这个变量副本,所以原来的Integer a变量还是原来的,仅仅是test这个方法里的副本变量变了,这么理解就清楚了。所以面试题2 输出88。
● 【文章汇总】面试篇
● 【文章汇总】Java基础篇
● 【文章汇总】性能调优篇
● 【文章汇总】设计模式篇
● 【文章汇总】Spring家族篇