
正文
[Java]判断Integer值相等最好不用==最好使用equals
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
测试代码
Integer c = ;
Integer d = ;
Integer e = ;
Integer f = ; System.out.println(c == d);
System.out.println(e == f);
结果输出:
true false
Integer为对象判断是否相等还是使用equals最靠谱,int为基本类型,判断是否相等就是可以使用==
其中的原因:
static final Integer cache[] = new Integer[-(-) + + ];
static {
for(int i = ; i < cache.length; i++)
cache[i] = new Integer(i - );
}
}
这是源码中的,也就是说cache中已有-128到127,不在这范围的会新new ,这时可以理解比较是内存地址,
也就是是不是同一对象.
所以说当Integer的值不在-128到127的时候使用==方法判断是否相等就会出错,在这个范围之内的就会没有问题!!!






