向下转型和自动包装

问题说明

在debug的时候遇到一个傻逼的问题,排查很长时间没有找到具体的原因。最后发现使用判等2这种方式进行判断的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public boolean testNumEquals() {
Long num1 = 0L;
int num = 0;
// 判等1
System.out.println(num == num1);
// 判等2
System.out.printlb(num1.equals(0));
// 判等3
System.out.println(num1.equals(0L));
}

out:
true;
false;
true;

问题分析

在分析之前需要说明几个关键的名字自动拆箱,自动装箱,隐式类型转化 进行说明。

  • 自动装箱:

    将基本类型转化为该基本类型的实际包装类

    eg: int –> Integer

  • 自动拆箱

    将包装类型转化为该包装类的基本类型

1
2
3
4
5
6
7
8
9
public static void test() {
int a = 1;
Integer a1 = new Intger(1);
System.out.println(a == a1);
System.out.println(a1.equals(a));
}
out:
true;
true;

问题总结

  1. 进行== 操作的时候,会对Intger进行自动拆箱的操作,使用Integer.equals(int)进行比较的时候,会对int进行自动装箱的操作。
  2. 对于两个非new生成的Integer对象,进行比较时,如果两个变量的值在区间-128到127之间
1
2
3
4
5
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
  1. 对于Integer i = 100;的操作等同于Ineger i = Integer.valueof(100);