【Java】Integer的常量池
2016-04-05 09:37
555 查看
笔试的时候遇到一个问题:
输出结果是true true false true
提到了==与equals的区别,第一反应是String。
String s = new String("....")是分配在堆中不同位置的,==返回false。
String s = "..."; String ss = "..." 指向池中同一个空间,然会true
equals比较的是对象的值,而==比较的是对象本体(位置)。
Integer也有区别?
附上java的源码:
所以在此范围内的 == 返回true,范围外的 范围false。(当然,equals全部返回true)
同样,Short Long 的常量池范围也是-128~127。
Boolean 也实现了常量池的功能。毕竟只有true和false两个值
Character的范围0~127
Integer i1 = 127; Integer i2 = 127; Integer i3 = 128; Integer i4 = 128; System.out.println(i1==i2); System.out.println(i1.equals(i2)); System.out.println(i3==i4); System.out.println(i3.equals(i4));
输出结果是true true false true
提到了==与equals的区别,第一反应是String。
String s = new String("....")是分配在堆中不同位置的,==返回false。
String s = "..."; String ss = "..." 指向池中同一个空间,然会true
equals比较的是对象的值,而==比较的是对象本体(位置)。
Integer也有区别?
附上java的源码:
public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
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) { 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); } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); } private IntegerCache() {} }可以看出来 Integer 也有常量池 范围是 -128~127
所以在此范围内的 == 返回true,范围外的 范围false。(当然,equals全部返回true)
同样,Short Long 的常量池范围也是-128~127。
Boolean 也实现了常量池的功能。毕竟只有true和false两个值
Character的范围0~127
相关文章推荐
- Eclipse--Java注释模板设置详解
- MyEclipse的 at com.genuitec.eclipse.ast.deploy.core.Deployment.<init>错误解决办法
- Java设计模式:桥接模式
- spring 事务管理
- 如何在MyEclipse中反编译class文件
- FileReader用法
- Java学习·静态代码块
- 构造方法与非构造方法的比较
- java的一些缓存机制
- springMVC4(12)复杂对象和集合类型入参绑定
- java的System.getProperty()方法可以获取的值
- java运行环境的构建,命令台的基本操作。
- Eclipse下的java工程目录
- java学习二:类
- java中为什么byte的取值范围为-128~127
- Java之I/O流
- 通过反编译看Java String及intern内幕--费元星站长
- java环境变量设置
- Permission denied: win7下面eclipse上传本地文件到DFS && 运行M/R程序时出现的同样的错误解决方法
- spring mvc + mybatis 整合框架