Integer对象隐藏的面试题
来源:互联网 发布:sql 如何加一行合计 编辑:程序博客网 时间:2024/05/03 01:31
Integer对象隐藏的面试题
之前去一家公司面试,对方甩出一堆笔试题,其中有一道如下
Integer a = 10; Integer b = 10; System.out.println(a == b); Integer c = 128; Integer d = 128; System.out.println(c == d );
问你结果是神马,以我行走江湖多年经验(啊呸),这里面一定有坑,是套路,就算我侥幸猜对了,那帮老鸟也一定会在面试时再考我为什么。
本着知之为知之,不知为不知的精神,直接空在了那里,现在重新看了源码,才稍稍理解了
当你创建Integer对象时
public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
IntegerCache是什么鬼
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) { 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); } 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() {} }
看完上面两段代码,它的意思如果你定义的整型对象的值在[-128,127]之间,就直接返回IntegerCache.cache[]数组里面的某个元素,下标与值对应
在[-128,127]之外的Integer对象就不再是相同的了直接 return new Integer(i);
也就是说,如果你定义的整型对象的值在[-128,127]之间,编译器不会去再创建Integer对象,直接从IntegerCache缓存中取,哪怕你定义100个值相同的Integer对象,它都是取的同一个对象,so
Integer a = 10; Integer b = 10; System.out.println(a == b);
结果是true
而
Integer c = 128; Integer d = 128; System.out.println(c == d );
结果是false
为什么么要这么搞呢,或许是[-128,127]经常用到,Java的设计者为了提高性能就这么设计的,哎!鬼知道呢,或许就是为了出这么个面试题(哈哈)
以上为个人见解,有问题qq群511906138一起讨论
0 0
- Integer对象隐藏的面试题
- 面试题-Integer和int的区别
- 一道Integer面试题引发的对Integer的探究
- 一道Integer面试题引发的对Integer的探究
- 面象对象的面试题
- Java面试题之Integer
- Java-Integer-int面试题
- Java关于Integer面试题
- 一道关于Java中Integer缓冲区的面试题
- java 关于int和Integer的面试题
- java 面试题----Integer的“==”比较
- 面试题:Integer和int的区别?在什么时候用Integer和什么时候用int
- 面向对象的相关面试题
- 有关String对象的一个面试题
- 面试题-面向对象
- 面向对象面试题
- Java基础-Integer注意事项以及面试题
- String转换与Integer面试题
- 跟我一起写 Makefile(十四)
- 一个简单的IIR低通滤波器(matlab实现)
- Android检测当前VPN状态
- CppPrimer--算术运算符
- db2表空间、本地分区索引
- Integer对象隐藏的面试题
- Java语法测试小全
- VC中对话框里添加View(Scroll)
- C++-自动析构时的顺序
- HTML中的跑马灯效果(<marquee>标签)
- 【金融】指标体系-投资绩效评估体系建设
- C++之三五法则
- [.net 面向对象程序设计深入](26)Redis——基础
- dingyeye loves stone 尼姆博弈