【Java】20211014_ 从 Integer 说起
20211014_从Integer说起
写在前面
今天面试一家美团外包,仅仅在一面就被吊打。
没有问框架,就是聊项目和基础,输的很彻底,但是面完就两个字,服气。
自己菜了,还能说啥,但是往往让人成长的就是这些失败。
说回面试题(见代码块1-1):
[^代码块1-1]
Integer a = 100; Integer b = 100; System.out.println(a == b); a = 1000; b = 1000; System.out.println(a == b);
控制台打印输出(见代码块1-2):
[^代码块1-2]
true false
为什么两次输出结果不一样?
答案:
1、在Java中,**==**在对两个对象做比较时,比较的是两者的内存地址值,这是很重要的前提。
2、左边是Integer——整形包装类对象,右边是int值,这样的代码会触发Java的自动装箱功能,自动调用**Integer.valueOf()**方法(见代码块2-1)。(注:valueOf方法有三个重载方法,此处参数为int)
[^代码块2-1]
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
通过查看valueOf方法可以看出,Java会将传入的int值i与IntegerCache.low以及IntegerCache.high做比较,传入的int值大小不一样,返回的包装类对象也不一样。
通过翻看IntegerCache代码(见代码块2-2),发现IntegerCache.low = -128,IntegerCache.high = 127,且IntegerCache中用静态代码块将IntegerCache.cache初始化了。
[^代码块2-2]
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; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } catch( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. } } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); // range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache.high >= 127; } private IntegerCache() {} }
再回看代码块2-1:
- 当传入int值介于-127~128之间时,valueOf方法返回的是IntegerCache.cache这个数组中的对象中的某一个确定的对象,所以两值都为100时==返回true。
- 当传入int值不在规定范围-127~128时,valueOf方法返回的是new Integer(i),即每次都会new出一个新的Integer对象,所以两值都为1000时==返回false。
努力让自己不那么菜
欲速则不达,每天进步一点点。
加油
我就喜欢这样的面试,问点实际的
天,这问的也太深了,让我对未来转码农又增添了一个劝退的理由
学习了
八股文日常
厉害了我的哥
长知识了
🐂哇我的哥
考古