Reputation: 2437
There are several questions that are similar to this one here on S.O., but they don't quite answer what the code implementation is. I've looked at
Why isn't there a java.lang.Array class? If a java array is an Object, shouldn't it extend Object?
and
How are arrays implemented in java?
and they don't answer what the concrete implementations are.
I've downloaded the java source from OpenJDK, and I really can't find what I'm looking for. (Perhaps that part of the code is proprietary?)
my_arr[500]
what's the algorithm implemented to get the value at index 500?Thanks in advance!
Upvotes: 2
Views: 1624
Reputation: 65
my_arr[1] = "whatevs"; this will set the first element in the array to whatevs.
System.out.print(my_arr[500]);// my_arr[#] is the location in memory for element 500 in the array, call on it to get whatever information is stored there. (actually the actual 500 element would be out of bounds, the element you would be looking for is 499. as arrays always start at 0 and go to their set amount -1)
3.To delete information you would do what is done in one but set it to "null" or copy the array and simply leave out the parts you don't want to include.
You would use a method to do all of these things within a program to render another affect. What really needs to be understood that each element in an array can be an object or a primitive,i.e. a number value, like 10.
If all of this seems to basic to you then you need to be more precise with your question or simply explain what you are trying to do with arrays.
Upvotes: 0
Reputation: 5625
I will say its same as that of C
or C++
when we do int a[10];
or Object obj[10];
compiler allocates the block of memory equal to 10*sizeOf(int)
or 10*sizeOf(Object)
the address of first location in memory block is stored in a
. so basically a
becomes pointer. Note Java internally uses Pointers
.
then whenever we try to access a[5]
address of location is calculated as pointer arithematic.
a+5*(sizeOf(int))
or obj+5*(sizeOf(Object))
and then read sizeOf(int)
or sizeOf(Object)
bytes as value
Upvotes: 3
Reputation: 147154
There are no appends, inserts or deletes on arrays.
The address of my_arr[500]
in a reasonable implementation would be the base address of the object, plus a small offset for the header, plus 500 times the size of the array element. Obviously you need to do range checking - the offsets needs to be non-negative and less than the length of the array (stored in the header).
Upvotes: 6