Java Object and array memory location

旧巷老猫 提交于 2019-12-06 14:40:41

问题


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?

edit

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?


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/3444395/java-object-and-array-memory-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!