博客
关于我
为什么Java中1000==1000为false而100==100为true?
阅读量:536 次
发布时间:2019-03-09

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

在Java中,对象的相等性比较主要看引用的指向是否相同,而不是对象本身的值是否相同。然而,对于Java的Integer类,内部实现采用了一个优化策略,即对一个范围内的数使用共享对象,从而节省内存。具体来说,对于-128到127之间的整数值,Integer类维护了一个缓存池,这样每次请求一个整数时,都会优先从缓存中获取已经存在的对象。如果缓存中没有对应的对象,则会创建一个新的,然后存入缓存备用。

当我们执行以下代码时:

Integer a = 1000, b = 1000;System.out.println(a == b);  // 1Integer c = 100, d = 100;System.out.println(c == d);  // 2

结果显示a == b返回false,而c == d返回true。这并不是因为1000和100本身有差异,而是因为较大的整数值(如1000)不会被缓存,因此a和b指向了不同的对象实例。而对于较小的整数值(如100),由于IntegerCache机制的作用,c和d指向了同一个缓存对象。

为了理解这个机制,我们可以查看Integer类的内部实现。Integer类包含一个私有的内部类IntegerCache,其作用是缓存-128到127之间的所有整数对象。当创建Integer对象时,首先会尝试从缓存中获取,若找不到则创建新对象并存储在缓存中。这样,对于同一个值的多个Integer实例,会指向同一个缓存对象,从而导致==比较返回true。

然而,通过反射API可以绕过这个机制。例如:

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {    Class cache = Integer.class.getDeclaredClasses()[0];    Field myCache = cache.getDeclaredField("cache");    myCache.setAccessible(true);    Integer[] newCache = (Integer[]) myCache.get(cache);    newCache[132] = newCache[133];    int a = 2;    int b = a + a;    System.out.println(a + " + " + a + " = " + b);}

该代码通过反射获取IntegerCache的缓存字段,并修改其内容,模拟了解内存管理机制的行为。通过这种方式,可以更深入地理解IntegerCache的工作原理及其对Java内存管理的优化作用。

总结来说,Java对Integer类的缓存机制确实影响了对象比较的结果,这既是性能优化的体现,也需要开发者在编写代码时注意其潜在影响。

转载地址:http://gehiz.baihongyu.com/

你可能感兴趣的文章
NoSQL介绍
查看>>
Notepad++在线和离线安装JSON格式化插件
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 fatal: unable to connect to github.com 的解决方法
查看>>
npm install 报错 no such file or directory 的解决方法
查看>>
npm install报错,证书验证失败unable to get local issuer certificate
查看>>
npm install无法生成node_modules的解决方法
查看>>
npm install的--save和--save-dev使用说明
查看>>
npm node pm2相关问题
查看>>
npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
查看>>