Question

An arrayList in Java "holds" references to the Objects and not the actual Object data.

I was wondering if we can implement an arrayList in Java that can contain the Object data directly instead of references. Can Java Unsafe Class be used for this implementation? If yes, what would be the performance of this list in comparison to the existing Java arrayList?

Was it helpful?

Solution

Briefly, no.

Java only works with references for objects. What you're describing relies on the low-level control on memory allocation/usage permitting you to allocate a block of memory for 'n' entries. Java simply doesn't work like that - you never have control of the memory and the JVM is at liberty to move the objects within memory. You only ever deal with references.

Note also that objects containing references will refer to further distinct memory blocks, and so the concept of an object being contained within one contiguous memory block doesn't really exist here.

If you really want a byte array backed by memory, the DirectByteBuffer may be of use. It's a java.nio class built using the sun.misc.Unsafe class. Perhaps you could serialise/deserialise objects to it (calculating carefully the size in order to determine the indexing properly). But the serialisation cost would swamp any other saving, I would suspect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top