【Java】Integer的常量池
来源:互联网 发布:全境封锁 nge无法优化 编辑:程序博客网 时间:2024/05/08 06:59
笔试的时候遇到一个问题:
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
0 0
- 【Java】Integer的常量池
- Java Integer 常量池
- java常量池-Integer
- java常量池概念,String,Integer等包装类对常量池的应用
- java常量池概念,String,Integer等包装类对常量池的应用
- Java常量池——Integer
- Java常量池——Integer
- Java常量池详解之Integer缓存
- Integer常量池
- Integer常量池
- Java中int与Integer的区别及享元模式在常量池中的应用
- java的常量池
- Java的常量池
- java Integer自动拆箱引发的NPE以及常量池导致的判等问题[-128 127]为常量池
- java的字符串常量池
- java String的常量池
- java的常量池问题
- java常量池的理解
- iOS资料-插件&第三方&文章
- FileWriter
- 数据类型
- window下共享文件
- 一个war包远程部署的脚本
- 【Java】Integer的常量池
- Android 内存监测工具 DDMS --> Heap
- C++中二维数组的参数传递
- C/C++连接MySql数据库
- Git开篇:认识Git
- JavaScript进阶基础二
- ZOJ 题目分类
- UITableViewCell 复杂时,高度计算优
- java变量所占字节数及取值范围