简体   繁体   English

将整数添加到ArrayList时

[英]When adding an integer to ArrayList

I have a very stupid question here. 我在这里有一个非常愚蠢的问题。 When we add an int value to an ArrayList, will it create a new Integer object of that int value? 当我们将一个int值添加到ArrayList时,它将创建一个具有该int值的新Integer对象吗? For example: 例如:

int a = 1;
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(a);

In the code above, 'a' is a primitive type which has value 1, 'list' is an arraylist which contains elements of Integer type. 在上面的代码中,“ a”是具有值1的原始类型,“ list”是包含Integer类型元素的数组列表。 So when adding 'a' to 'list', how does 'list' treat 'a' as an Integer? 因此,在将“ a”添加到“列表”时,“列表”如何将“ a”视为整数?

The a is autoboxed to an Integer . a 装箱Integer From the link, 通过链接,

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. 自动装箱是Java编译器在原始类型及其对应的对象包装器类之间进行的自动转换。

Whether a new Integer object is created depends on the value if the int being added. 是否创建新的Integer对象取决于要添加int的值。 The JVM has a cache of premade objects covering a range of common values, and if the value is in that range it will use the existing cached object instead of creating a new one. JVM具有一个覆盖一系列公共值的预制对象的缓存,如果该值在该范围内,它将使用现有的缓存对象而不是创建一个新的对象。

For the int type, the Java language specification requires that this cache cover all numbers from -128 to 127 (inclusive). 对于int类型, Java语言规范要求此高速缓存必须覆盖从-128到127(含)之间的所有数字。 A JVM implementation may or may not include additional values in this cache, at its option. JVM实现可以选择是否在此缓存中包含其他值。

In

int a = 1;
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(a);

the last line is automatically converted by the compiler into: 最后一行由编译器自动转换为:

list.add(Integer.valueOf(a));

Integer.valueOf is a method that either creates a new Integer object with the same value, or reuses one that already exists. Integer.valueOf是一种方法,该方法可以创建一个具有相同值的新Integer对象,或者重用已经存在的对象。 The resulting object has no relation to the variable a , except that it represents the same value. 所得对象与变量a无关,只是它表示相同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM