Tuesday, September 22, 2020

int[] and Integer[] arrays - What is the difference?

This image should help you to understand the difference:






int is a number, it's a primitive type.

Integer is an object.

When you have an array of Integers, you actually have an array of objects. Array of ints is an array of primitive types.

Since arrays are objects, they're allocated on the heap. If it's an array of ints, these ints will be allocated on the heap too, within the array.

Further adding. to this..

There is a difference at run-time.

int[] is an array of primitive int values. Integer[] is an "object" array, holding references to Integer objects.

Most important practical difference: int[] cannot hold null values.

int[] does store primitive types. And the array itself lives on the heap. However, those primitives are allocated as part of the array. They are not stored separately elsewhere on the heap. This is very similar to how a primitive field is part of an object instance: The object is on the heap, and its field is an integral part of that object (whereas for a non-primitive field, only the reference is stored inside the object and the target instance that reference points at is stored separately on the heap).


Ref : this link

No comments:

Post a Comment