When adding an integer to ArrayList

本秂侑毒 提交于 2020-02-16 06:44:13

问题


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? 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. So when adding 'a' to 'list', how does 'list' treat 'a' as an Integer?


回答1:


The a is autoboxed to an Integer. From the link,

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.




回答2:


Whether a new Integer object is created depends on the value if the int being added. 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.

For the int type, the Java language specification requires that this cache cover all numbers from -128 to 127 (inclusive). A JVM implementation may or may not include additional values in this cache, at its option.




回答3:


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. The resulting object has no relation to the variable a, except that it represents the same value.



来源:https://stackoverflow.com/questions/35978451/when-adding-an-integer-to-arraylist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!