1、运行案例:
这到底是为什么那?我们对照Integer的源码进行分析
2、源码分析
通过源码我们能够看到,在valueOf方法里面有一个条件判断,通过代码查找发现 IntegerCache.low是-128, IntegerCache.high是127 ;也就是说如果值是在-128到127之间的值会直接从cache缓存中取,如果不是会重新new创建对象。
3、那为什么默认是-128和127之间的数值那?JDK为何要这样做?
在Java API中的解释是这样的:
Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range
大致意思是这样的:
-128到127的数据在int范围内是使用最频繁的,为了减少频繁创建对象带来的内存消耗,这里其实是使用了享元模式,以提高空间和时间性能。
在JDK中这样应用的不止int,图片如下:
参考:两个Integer对象比较大小,为什么100等于100,1000不等于1000 ?
最后
以上就是悲凉雪碧最近收集整理的关于两个Integer比较大小,为什么100等于100,1000不等于1000?的全部内容,更多相关两个Integer比较大小内容请搜索靠谱客的其他文章。
发表评论 取消回复