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;
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.
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.
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.