本来已经写过128陷阱的博客了,但是上周在实际开发的时候遇到了一个bug,然后自已眼看数据库的id值,在128以前的数据是没有问题的,但是在128以后的数据就会莫名的丢失。
首先让我们看一小段代码:
public static void main(String[] args) {
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a == b);
System.out.println(c == d);
}
来看看打印的结果:
这里可以看出在int的包装类Integer在127的时候是可以使用==去判断两个数是否相等的,而在Integer是128的时候就不能去判断这两个数是否相等。如果要问他的原因,让我们读一下源码:
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
可以看下注释注释中也有说明,我们自己来看一下这个自动装包的方法valueOf,IntegerCache.low和IntegerCache.high可以在上面代码定义中看到,定义的为-128和127,当然也可以通过代码得知,读代码可知,如果这个数实在-128到127之间则直接返回这个已经定义在数组中的值,而不再这个范围中则需要去new一个新的对象,我们知道在java中==比较额是储存对象的地址,在大于等于128的情况下他其实是new了两个对象,他们的 == 判断自然是不可取的,这里我们要判断应该是使用equals。
看一下实际开发中遇到的bug
List<AdminRolePermissionResponse> list1 = new ArrayList<>();
for (AdminPermission adminPermission : list) {
if(adminPermission.getRefPermissionId() == parentId){
/*业务代码*/
}
}
return list1;
}
我们看一下这句adminPermission.getRefPermissionId() == parentId,这里我们使用的数据类型是Long类型,Long是long的包装类和integer是一样的性质,使用这种方法会有一个问题就是当数据大于128的时候会不走下面的业务代码导致数据丢失所以这里应该改成equals。