目录
一、Integer自动装箱的坑
项目场景:
比较两个数据包明细数据的数量的时候,有同事踩了自动装箱方法valueOf()的坑。因为平常明细数量都是小于128的,所以没有问题,但是某天突然出现一笔明细量超过128的,直接导致比较结果出错。
问题描述:
两个包的明细数据的数量都用Integer来存放,最后比较两个数量的大小是否相同。结果发现如果数值小于128的整数时,比较结果是正确的,当数值大于等于128的时候,比较结果就不正确了。代码示例如下:
public class Test {
public static void main(String[] args){
Integer i1 = 2;
Integer i2 = 2;
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i1==i2);
System.out.println(i3==i4);
}
}
输出:
true
false
原因分析:
1、Integer在涉及int基本类型的时候,都会触发自动拆装箱。例如Integer与int用==比较的时候,就会触发Integer自动拆箱为int然后再进行比较。Integer用int初始化的时候又会触发自动装箱操作,将int转化为Integer再赋值给Integer。代码示例如下:
public class Test {
public static void main(String[] args){
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i3==i4);
System.out.println(i3==128);
}
}
输出:
false
true
2、查看Integer的源码,你会发现Integer内部缓存了一组Integer对象,缓存的Integer对象的值区间为-128~127,因为作者认为这个范围的整数值是使用最频繁的。当涉及到自动装箱的时候,如果数值在-128~127区间内,则直接返回缓存的对象,如果超出范围才会重新new一个对象返回。Integer源码贴在下方:
自动装箱源码:
public static Integer valueOf(int i) {
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) {
try {
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);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
解决方案:
如果数值范围有可能超出128,则不使用自动装箱来获取对象,而是通过new来创建对象。
public class Test {
public static void main(String[] args){
Integer i1 = new Integer(2);
Integer i2 = new Integer(2);
System.out.println(i1==i2);//对象比较
System.out.println(i1.intValue()==i2.intValue());//值比较
}
}
同样的,Long,Short也有它们的缓存区间。
总结:虽然包装类我们平时用起来非常方便,但是不能忘记它们的本质是属于对象而不是基本数据类型。
二、泛型遇上可变长参数
项目场景:
数据总线的getData方法的返回值类型为泛型T,日志打印的时候需要打印返回的值。
问题描述:
当我们打印日志的时候,喜欢采用比较优雅的方式用{}来占变量的位置,而不是通过+来进行字符串连接。如果变量时一个返回值的时候,这种写法就会报错,并且是在运行的时候报错而不是编译的时候,让人特别容易忽略错误。
public class Logger {
public static void main(String[] args){
Logger.info("{}",getT());
}
public static <T> T getT(){
return (T)"5";
}
public static void info(String s,Object... o){
System.out.println(s);
}
}
输出:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object; at temp.Logger.main(Logger.java:9)
原因分析:
1、泛型一开始不指定具体的参数或者返回值类型,而是使用或者调用的时候传入具体的类型。如下面例子:
public class Logger {
public static void main(String[] args){
System.out.println((Integer) getT());
}
public static <T> T getT(){
return (T)"fff";
}
}
输出:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at temp.Logger.main(Logger.java:9)
2、getT()方法拿到的是一个泛型的结果,当使用的时候才能真正确定泛型对应的实际的值,会发生强制转换,而可变长参数遇到泛型的时候会默认将其转换为数组,如果转换不成功则抛错。
解决方案:
调用带有可变参数的方法时,如果传入的是泛型,先指定正确的类型后才传入需要调用的方法。
public class Logger {
public static void main(String[] args){
info("输出的值为{}",(String)getT());
}
public static <T> T getT(){
return (T)"fff";
}
public static void info(String s, Object... o){
System.out.println(s+o[0]);
}
}
输出:
输出的值为{}fff
总结:使用泛型的时候,一定要小心类型转换出错的问题,特别是小心编译的时候不报错的错误。