Java中那些不得不说的坑
来源:互联网 发布:hold the door知乎 编辑:程序博客网 时间:2024/05/13 05:51
看看下面这段代码跟你想的结果一样吗?
Integer a =127; Integer b = 127; System.out.println(a==b);//true Integer a1 = 128; Integer b1 = 128; System.out.println(a1==b1);//false
为什么会是这样的结果,我们反编译.class文件看看
Integer a = Integer.valueOf(127); Integer b = Integer.valueOf(127); System.out.println(a == b); Integer a1 = Integer.valueOf(128); Integer b1 = Integer.valueOf(128); System.out.println(a1 == b1);
其实是Integer作者在写这个类时,为了避免重复创建对象,对一定范围的Integer做了缓存,如果该值没有在该范围内则new一个新对象返回,从源码中可以看到如下代码:
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; //i如果在该范围内直接返回缓存值 return new Integer(i); }
IntegerCache 是Integer 类的静态内部类,再来看看IntegerCache的实现
private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static {//当类被载入到java虚拟机是进行缓存创建 // 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() {} }
阅读全文
0 0
- Java中那些不得不说的坑
- java异常那些不得不说的事
- 不得不说的那些坑(一)
- coding中那些不得不说的愚蠢的mistake(1)
- 这四年不得不说的那些事
- IE6不得不说的那些BUG
- 不得不说的opencv 那些事
- 唐骏:这四年不得不说的那些事
- 我与朗科不得不说的那些事儿
- 和小媳妇的那些不得不说的事
- 关于豆瓣不得不说的那些事儿
- Android Service那些不得不说的事-之一
- 做好用户体验不得不说的那些事
- 关于简历不得不说的那些事儿
- 安卓listView不得不说的那些细节
- printf与a++那些不得不说的事儿
- Java中与String有关的且不得不说的事
- 不得不说的Java环境变量配置
- 与eclipse集成的管理zookeeper工具zookeeperBrowser
- linux 下 dd命令用法
- Linux下的常用替换命令
- Java并发之神修炼之路---创建多线程的三种方式
- Android常用系统广播
- Java中那些不得不说的坑
- 实战Java高并发程序设计(二)Java并行程序基础
- 输出逆序数
- 初学html
- 工厂方法模式
- maven创建父子结构工程
- C语言关于static的解析
- 数据库基础知识点(2)
- Spark面试经典系列之数据倾斜解决方案的“银弹”是什么? 本节我们对Spark数据倾斜解决方案进行回顾和总结