/**
*
* The Advantages and Traps of Autoboxing
*
* 优点
* 代码更简洁
* 自动使用最优的转换代码(比如使用IntegervalueOf(int)而不是使用new Integer(int))
*
* 缺点:
* 如果不注意可能会导致错误
* 如果不注意可能会导致效率低下
* 有时需要强制类型转换
*
* 参考advantagesandtrapsofautoboxing/
*
*/
public class M {
public static void main(String[] args) {
// 导致错误
Long longValue = L;
Systemoutprintln(longValueequals(L)); // true
Systemoutprintln(longValueequals()); // false
Systemoutprintln(longValue == L); // true
Systemoutprintln(longValue == ); // true
long t;
long t;
// 导致效率低下
// 实验组
t = SystemcurrentTimeMillis();
Long counter = L; // Long counter = ; 会报错!!!
for (long i = ; i < ; i++) {
counter++; // 等价于 LongvalueOf(counterlongValue() + )
}
t = SystemcurrentTimeMillis();
Systemoutprintln(time = + (t t)); //
// 实验组
t = SystemcurrentTimeMillis();
long counter = ;
for (long i = ; i < ; i++) {
counter++;
}
t = SystemcurrentTimeMillis();
Systemoutprintln(time = + (t t)); //
// Integer : + =
// 需强制类型转换否则调用printSum(long long)
// 强制转换为 int也会调用printSum(long long)
printSum((Integer) (Integer) );
// Long : + =
printSum(L L);
// 需强制类型转换
// Long : + =
printSum((Long) L (Long) L);
// Float : + =
printSum(F F);
// Double : + =
printSum(D D);
}
public static void printSum(long a long b) {
Systemoutprintln(Long : + a + + + b + = + (a + b)); // true
}
public static void printSum(Long a Long b) {
Systemoutprintln(Long : + a + + + b + = + (a + b)); // true
}
public static void printSum(Integer a Integer b) {
Systemoutprintln(Integer : + a + + + b + = + (a + b)); // true
}
public static void printSum(Float a Float b) {
Systemoutprintln(Float : + a + + + b + = + (a + b)); // true
}
public static void printSum(Double a Double b) {
Systemoutprintln(Double : + a + + + b + = + (a + b)); // true
}
}