Integer 缓存(IntegerCache)是 Java 5 中引入的一个有助于节省内存、提高性能的特性
废话不多说,看一个栗子
/**
* @author :Vimonster
* @time : 2019/12/19 10:41
* @slogan: 任时间再怎样低头呢喃,也要不挥泪后风雨兼程
* @description:
*
* 关于Integer 和 int 的一些注意事项
*
*/
public class IntegerBug {
public static void main(String[] args) {
test1();
test2();
}
/**
* 比较值问题
*
*/
private static void test1(){
Integer a = 110;
int b = 110;
Integer c = new Integer(110);
System.out.println(a == b); //true 此处相等 应为Integer在和int比较时会自动拆箱 变为int 此处a自动拆箱为int类型 对象的比较也就变成了值的比较
System.out.println(a == c); //false 因为c使用了new对象 c的值其实在堆空间 而 a 的值在常量池 两个都是对象 对象地址不一样 所以是false
}
/**
*
* -128与127之间,Integer会自动存在IntegerCache.cache 直接从内存中去取,不在这个范围则会new新对象
*
*/
private static void test2(){
int a = 127;
int b = 127;
Integer c = 127; //编译的时候 翻译为:Integer c = Integer.valueOf(127);
Integer d = new Integer(127);
Integer e = 127;
System.out.println(a == b); //true
System.out.println(a == c); //true
System.out.println(c == d); //false
System.out.println(a == d); //true