软件编程
位置:首页>> 软件编程>> java编程>> Java Integer及int装箱拆箱对比

Java Integer及int装箱拆箱对比

作者:bf378  发布时间:2023-04-22 04:21:11 

标签:java,Integer,int

示例代码:


class BoxIntInteger {

public static void main(String[] args) {

Integer a = new Integer(10111);
   int b = 10111;
   boolean equal1 = a == b;
   boolean equal2 = a.equals(b);
   System.out.println(equal1);
   System.out.println(equal2);
 }
}

反编译字节码:


public static void main(String args[])
{
 Integer a = new Integer(10111);
 int b = 10111;
 boolean equal1 = a.intValue() == b;
 boolean equal2 = a.equals(Integer.valueOf(b));
 System.out.println(equal1);
 System.out.println(equal2);    
}

1:可以看出对于Integer与int使用==比较大小的话,优先Integer拆箱。

2: 如果使用equals比较大小的话,则int装箱。

提示:对于Integer与int之间大小比较优先使用equals比较,否则容易出现空指针,例如:

Integer c= null;
System.out.println(c==1);

原因:由于Integer需要调用intValue进行拆箱,因而空指针。

Integer与Integer必须使用equals方法比较,这个就不必解释了。但是通常我们可以看先Integer与Integer之间使用==也可以正确比较,原因是:Integer对于-128到127之间的数字在缓存中拿,不是创建新对象。

缓存获取数据源码:java.lang.Integer#valueOf(int)


public static Integer valueOf(int i) {
 if (i >= IntegerCache.low && i <= IntegerCache.high)
   return IntegerCache.cache[i + (-IntegerCache.low)];
 return new Integer(i);
}

来源:https://www.cnblogs.com/leodaxin/p/9088036.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com