I'm trying to understand the array setup in java. Why must you initialize space for each each object in the array, after you have created the array. How is it stored in memory like this:
[object][object]
or like this:
[*class]->[object]
[*class]->[object]
In other words, what is actually being done in memory. Does array[0] = new class()
just return a reference to a reserved location in memory, and the class[] array = new class[10]
statement create something along the lines of 10 pointers, which are later assigned to by the new statements?
An array stores its elements in contiguous memory locations. If You created the array locally it will be on stack. Where the elements are stored depends on the storage specification.
In Java, arrays are objects, therefore just like other objects arrays are stored in heap area.
Arrays are often represented with diagrams that represent their memory use. The diagram below is one typical way to represent the memory used by an array. Each box represents the amount of memory needed to hold one array element. For ints this is usually 4 bytes.
An array elements are always stored in sequential memory locations. Hence, the correct answer is option (A)
If you are familiar with C/C++ you can think of Java object references as pointers to objects (or pointers to structs). So:
Person p = new Person();
p.setName("Helios");
is:
So when you are doing:
Person[] ps = new Person[5];
you are reserving an array of 5 references to Person. Next you will have to create each real person and assign each reference to a place in the array.
Edit: the (almost) C/C++ version of the previous code
class Person { ... };
typedef PersonStruct* Person; // I don't remember if this declaration is ok
Person p = new PersonStruct();
p -> setName(...);
Person[] ps = new Person[5];
// ps is a variable in the stack pointing to the array in the heap
// (being the array five references to the PersoStruct)
and you could do
ps[3] = p;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With