listofIntegers.add(ValueOf(50)); 之间有什么区别?和 listofIntegers.add(50);在 Java

What is difference between of listofIntegers.add(ValueOf(50)); and listofIntegers.add(50); in Java

这两个代码有什么区别:

Arraylist<Integer> listofIntegers = new Arraylist<Integer>();
listofIntegers.add(666);
System.out.println("First Element of listofIntegers = " + listofIntegers.get(0));

Arraylist<Integer> listofIntegers = new Arraylist<Integer>();
listofIntegers.add(Integer.ValueOf(666));
System.out.println("First Element of listofIntegers = " + listofIntegers.get(0));

两者的输出相同

谢谢。

装箱转换隐式使用Integer.valueOf,所以两者没有区别。

例如,考虑以下代码:

public static void main(String[] args) {
    Integer x = 100;
    Integer y = Integer.valueOf(100);
}

它的字节码(如javap所示)是:

public static void main(java.lang.String[]);
    Code:
       0: bipush        100
       2: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       5: astore_1
       6: bipush        100
       8: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
      11: astore_2
      12: return

如您所见,这两段代码是相同的。

尽管 language specification section on boxing 不保证它会被 valueOf 实现,它 确实 保证有限的缓存:

If the value p being boxed is the result of evaluating a constant expression (§15.28) of type boolean, char, short, int, or long, and the result is true, false, a character in the range '\u0000' to '\u007f' inclusive, or an integer in the range -128 to 127 inclusive, then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.

这与Integer.valueOf所做的保证相同。