Arrays are contiguous sections within memory, so to create an array you would need to reserve a chunk of memory which is of size n * sizeof(type)
, where n
is the amount of items you would like to store and the sizeof(type)
would return the size, in bytes which the JVM would need to represent that given type.
You would then store a reference (pointer) to the first location of your memory segment, say 0x00
, and then you use that as a base to know how much you need to move to access the elements, so a[n]
would be equal to doing 0x00 + (n * sizeof(type))
.
The problem with trying to implement this in Java is that Java does not allow pointer manipulation, so I do not think that building your own array type would be possible since you cannot go down to that level.
That being said, you should be able to create a linked data structure, where the nth
element points to the (n + 1)th
element.
Other problems why you should try other languages, such as C#
(check unsafe
operations), C++
or C
:
- To my knowledge, Java does not have a
sizeof
function (see this).
- Java does not allow
operator overloading
. So you cannot define your own indexing operators such as [index]
. You would probably need to do something like array.getElementAt(0)
to get the first element.
As @ug_ recommended, you could take a look at the Unsafe class. But also as he recommended, I do not think that you should do pointer arithmetic with a language which has pointer abstraction as one of its core ideas.