java - Integers.add(Value Of(50))列表之间有什么区别?和 Integers.add(50) 列表;在 java

标签 java arraylist autoboxing

这两个代码有什么区别:

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 做出的保证相同.

关于java - Integers.add(Value Of(50))列表之间有什么区别?和 Integers.add(50) 列表;在 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48251511/

相关文章:

java - Spring Boot 中的 Hibernate JPA/CrudRepository 实体锁定

java - 如何在 Selenium 中处理 IFrame 和 LoadableComponent?

java - Java 中的 ADT 理解 - 将元素添加到 Arraylist 的尾部

java - 如果我从另一个类调用它,为什么我的 ArrayList 是空的?

java - 自动装箱和重载

Java日历不清除一天中的小时

java - Stars.java 数组索引越界

string - 长度无法解析或不是字段(ArrayList get 函数)

java - 在自动装箱中,转换是基于我们分配给的变量/引用还是相反?