【问题标题】:What is the need of an intValue() method if wrappers use unboxing?如果包装器使用拆箱,那么需要什么 intValue() 方法?
【发布时间】:2013-04-13 08:41:17
【问题描述】:

例如看这段代码:

Integer myInt = new Integer(5);
int i1 = myInt.intValue();
int i2 = myInt;
    
System.out.println(i1);
System.out.println(i2);

如您所见,我有两种方法可以将整数值从包装器复制到原始值:

我可以使用unboxing

我可以使用Integer#intValue()的方法。

那么在已经开箱的情况下还需要一个方法呢?

【问题讨论】:

    标签: java integer wrapper unboxing


    【解决方案1】:

    Java 5 中引入了拆箱。自original release 以来,包装器(包括此方法)一直存在。

    Javadoc的链接

    在那个时候(1996 年),我们确实需要 intValue() 方法,因为 Oracle 保证向后兼容...达到一定水平(在主要版本中并不总是 100%)。

    方法必须保留。

    【讨论】:

    • 所以,今天我想在 JDK7 中使用拆箱比使用旧的 intValue() 更好。
    • @user1883212 就像 DeltaLima 在他的回答中显示的那样,装箱/拆箱可能会产生一些奇怪的结果,只要您知道自己在做什么,就可以随意使用这两个系统中的任何一个。
    【解决方案2】:

    除了 Frank 的回答提供了一个很好的历史视角之外,今天在某些情况下仍然需要使用 intValue()

    请注意以下表明您不能将Integer 视为int 的陷阱:

     Integer i1 = new Integer(5);
     Integer i2 = new Integer(5);
    
     //This would be the way if they were int
     System.out.println(i1 == i2); //Returns false
    
     //This is the way for Integers
     System.out.println(i1.intValue()==i2.intValue()); //Returns true
     System.out.println(i1.equals(i2)); //Returns true
    

    返回

    false
    true
    true
    

    【讨论】:

    • 谁知道这引起了多少不解的目光和挠头。在对容器进行索引并尝试比较值时意外地遇到这种情况是相当典型的。例如。 List<Integer> A; A.get(i) == A.get(i - 1) 返回 false 即使两个位置都包含 Integer(5)...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多