博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在Java中==的一个坑
阅读量:4677 次
发布时间:2019-06-09

本文共 2165 字,大约阅读时间需要 7 分钟。

 

观察下面代码,输出结果是什么?

 

public static void main(String[] args) {        Integer p = 10000;        Integer q = 10000;        System.out.println(p == q);        System.out.println(p.equals(q));    }

 

运行一次,答案与预想的完全不一样。在比较数字的时候,一定要用euqals,不能用==c

 

查看Integer的jdk源码,发现如下片段:

/**     * Cache to support the object identity semantics of autoboxing for values between     * -128 and 127 (inclusive) as required by JLS.     *     * The cache is initialized on first usage.  The size of the cache     * may be controlled by the {
@code -XX:AutoBoxCacheMax=
} option. * During VM initialization, java.lang.Integer.IntegerCache.high property * may be set and saved in the private system properties in the * sun.misc.VM class. */ 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() {} }

这儿的IntegerCache有一个静态的Integer数组,在类加载时就将-128 到 127 的Integer对象创建了,并保存在cache数组中,一旦程序调用valueOf 方法,如果i的值是在-128 到 127 之间就直接在cache缓存数组中去取Integer对象。

 

如果是-128 到 127 的值,你不管创建多少个这个范围内的Integer用ValueOf出来的都是同一个对象。

转载于:https://www.cnblogs.com/xcr1234/p/6384705.html

你可能感兴趣的文章
详解JS设计模式
查看>>
CPSR寄存器
查看>>
Java基础50题test7—处理字符串
查看>>
保险行业电话外呼型呼叫中心方案
查看>>
自建型呼叫中心
查看>>
input file 文件上传,js控制上传文件的大小和格式
查看>>
Day 6 函数与模块
查看>>
java类中final方法的作用
查看>>
【58同城模拟】第一日。框架。
查看>>
MVC---- DataSet 页面遍历
查看>>
WebApi请求原理
查看>>
[Node.js] node-persist: localStorage on the server
查看>>
jquery.event 研究学习之bind篇
查看>>
LOJ #108. 多项式乘法
查看>>
军事机密(Secret.pas)
查看>>
正向代理和反向代理
查看>>
@RequestParam、@RequestBody和@ModelAttribute区别
查看>>
.net 缓存
查看>>
egret 取消自动连接github
查看>>
libusb开发指南
查看>>