Integer在与Integer比较的时候是比较内存地址,Integer与int比较的时候Integer会产生自动拆箱进行值比较,如果使用不当,这期间就会产生一些不易察觉的问题,下面将详细介绍。
先看一个Integer缓存样例
public static void main(String[] args) {
Integer a0 = 100;
Integer b0 = 100;
System.out.println(a0== b0);
// out => true
Integer a1 = 1000;
Integer b1 = 1000;
System.out.println(a1 == b1);
// out => false
}
有很多资料可以说明原理,这里不再赘述,这里想说的是Integer的自动拆箱封箱有很多需要注意的点,这些点都比较隐蔽,使用稍有不慎就会埋藏bug,切不易发现。
下面介绍几种拆箱问题
1. 方法参数使用int
因为一般PO、DTO都是使用Integer,所以在方法调用的时候会产生NullPointerException异常,解决办法是方法参数使用Integer
public class Main{
static Integer a = null;
public static void main(String[] args) {
test(a); // java.lang.NullPointerException 异常
}
public static void test(int aaa){
System.out.println(aaa);
}
}
2. 枚举使用Integer
枚举使用Integer与实体类的Integer比较时,就会出现地址比较,而这常会被误使用为值比较,埋藏bug。
解决办法为枚举使用int类型。
public class Main{
static Integer a = null;
public static void main(String[] args) {
Integer status = 1000;
System.out.println(status == StatusEnum.Error.getCode()); // out => false
}
public enum StatusEnum{
Error(1000);
private Integer code;
StatusEnum(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
}
}









网友评论