Java Integer之间==问题
2016-03-21 15:56
489 查看
public class Main { public static void main(String[] args) { Integer i = 1000 ; Integer j = 1000 ; Integer x = 100 ; Integer y = 100 ; Integer m = new Integer(100) ; Integer n = i ; System.out.println(i==j); System.out.println(x==y); System.out.println(x==m); System.out.println(i==n); } }
输出:
false true false true
源码 //如果是在-128到正的127之间就返回缓存里面的值。 public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) { // must cache return IntegerCache.cache[i + offset]; } return new Integer(i); } //缓存的代码 private static class IntegerCache { private IntegerCache(){} static final Integer cache[] = new Integer[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Integer(i - 128); } }
在-128<=i<=127的时候是直接用的int原始数据类型,而超出了这个范围则是new了一个对象。
java对小整形对象的优化, [-128,127]这个范围的整数值在程序中出现次数多,这样处理可以减少内存中对象的数量。
相关文章推荐
- Spring常用注解
- 圣思源-张龙-Java SE 第九讲(面向对象之封装)
- struts2 <s:iterator> status属性
- java集合-ArrayList的实现原理
- 圣思源-张龙-Java SE 第八讲(理解面向对象程序设计)
- spring jar包详解
- AndFix Eclipse 版
- springMVC—注解开发实例
- 圣思源-张龙-Java SE 第七节(流程控制语句 续 Flow Control Statement Cont.)
- java 导入项目路径配置
- 圣思源-张龙-Java SE 第六节(流程控制语句 Flow Control Statement)
- Java中@Override的作用
- Java Set集合去重机制
- Java hashCode
- java0x01 eclipse基本操作
- Java 动态代理机制分析及扩展
- java中将String和int转换的方法
- ThreadPoolExecutor中运行线程名称的修改
- JVM内幕:Java虚拟机详解
- JAVA学习笔记