2

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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so the compiler will create a new object in the heap, which has no relation to the variable a, it that correct?
Regardless of whether a new object is created (there must be a cache for values in the range of byte), the intValue() will equal a so they're related. And, if unboxed, then the value will also equal a.
0

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.

1 Comment

Thanks for your answer
0

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.

1 Comment

Thank you for answering, that helps me to understand

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.