Home > OS >  Is java array elements always stored in contiguous memory incase of reference types?
Is java array elements always stored in contiguous memory incase of reference types?

Time:12-05

I've read that The elements of an array are stored in a contiguous memory location . Is it always the case ? I understand this is the case with array of primitives. I'm a bit confused about array of objects. An array of objects basically contains reference of the real objects right? references must be stored in contiguous locations but what about the real objects are they really stored in contiguous locations?

CodePudding user response:

Is it always the case ?

Yes, but keep reading.

I'm a bit confused about array of objects. An array of objects basically contains reference of the real objects right? references must be stored in contiguous locations but what about the real objects are they really stored in contiguous locations?

Exactly, what the array contains is object references, not the objects themselves. Think of object references as being similar to long values that tell the JVM where the object is elsewhere in memory (it's more complicated than that, but that's a useful mental model). The object references are stored in the array's contiguous memory block. The objects are elsewhere, and may or may not be stored in contiguous memory (probably not).

So for instance, say we have:

int[] a = new int[] { 1, 2, 3 };

In memory we'll get something like:

                −−−−−−− 
a: Ref51234−−−>| int[] |
                −−−−−−− 
               | 1     |
               | 2     |
               | 3     |
                −−−−−−− 

a contains a reference to the array, which is elsewhere in memory and has a contiguous data block containing 1, 2, and 3.

Now let's look at an object array (where the Example class stores the given constructor parameter as a private x field):

Example[] a = new Example[] { new Example(1), new Example(2), new Example(3) };

That might give us something like this:

                −−−−−−−−−−−            −−−−−−−−− 
a: Ref51234−−−>| Example[] |      −−−>| Example |
                −−−−−−−−−−−      |     −−−−−−−−− 
               | Ref81372  |−−−−−     | x: 1    |
               | Ref96315  |−−−−       −−−−−−−−−    
               | Ref12975  |−−  |                    −−−−−−−−− 
                −−−−−−−−−−−   |  −−−−−−−−−−−−−−−−−−>| Example |
                              |                      −−−−−−−−− 
                              |                     | x: 2    |
                              |                      −−−−−−−−− 
                              |    −−−−−−−−− 
                               −−>| Example |
                                   −−−−−−−−− 
                                  | x: 3    |
                                   −−−−−−−−− 

Some environments have packed arrays as an adjunct. For instance, IBM documents packed arrays for its environment here.

  •  Tags:  
  • java
  • Related