What is the difference between listofIntegers.add (ValueOf (50)); and listofIntegers.add (50); in java

What is the difference between these two codes:

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

and

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

Both of them have the same conclusion.

Thanks.

+6
source share
1 answer

Boxing conversion uses Integer.valueOfimplicitly, so there is no difference between the two.

For example, consider this code:

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

Bytecode for this (as shown 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

As you can see, the two parts of the code are identical.

Although the language section of the box specification does not guarantee that it will be implemented valueOf, it does guarantee limited caching:

p, , (§15.28) boolean, char, short, int, or long, , false, '\ u0000' '\ u007f' -128 127 , a b p. , a == b.

, Integer.valueOf.

+21

All Articles