Reputation: 336
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?
Upvotes: 2
Views: 2270
Reputation: 58878
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.
Upvotes: 0
Reputation: 5087
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.
Upvotes: 0
Reputation: 201447
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.
Upvotes: 1