Tutorial :Java Object and array memory location


I'm writing an array-backed hashtable in Java, where the type of key and value are Object; no other guarantee.

The easiest way for me code-wise is to create an object to hold them:

public class Pair {       public Object key;      public Object value;  }  

And then create an array

public Pair[] storage = new Pair[8];

But how does the jvm treat that in memory? Which is to say, will the array actually:

  • be an array of pointers to Pair() objects sitting elsewhere, or
  • contain the actual data?


Since the objects are instantiated later as new Pair(), they're randomly placed in the heap. Is there any good way to ensure they're sequential in the heap? Would I need to do some trickery with sun.misc.unsafe to make that work?

Explaining my motivation, if I want to try and ensure that sequential items are in the same page of memory, is there any way to do this in Java?


The array will be an object on the heap containing pointers to the Pair objects which will also be on the heap (but separate from the array itself).


No, the storage array will only contain pointers to the actual Pair objects existing somewhere else on the heap. Yet, remember to instantiate 8 Pair objects and make each element of the array point to these objects. You need to have something like this after the code that you have written:

for(int i=0;i<storage.length;i++)      storage[i] = new Pair() ;  

Only then will the Pair objects be created and correctly referred to by the storage array.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »