As far as I can see the JVM reserves for each field the requiered memory for one instance of MyObject so a lot of memory is reserved even though it is never really used.
No, it doesn't. It reserves enough memory for 100 object references, not 100 instances of MyObject
. An object reference is not big (32 or 64 bits, see this answer for details). ASCII-art below.
Now, if you're bothered by even reserving 100 slots that are the size of an int
or long
, you could use ArrayList
which will reallocate a backing array as necessary (but this can add to memory fragmentation), a LinkedList
which doesn't use an array at all (but has higher memory overhead for the entries that it does have), or even a structure such as a Map
that doesn't (necessarily) use arrays at all (but again has higher overhead per entry).
ASCII-art and details for the 100-place array:
So when you first create that array, here's what you have in memory:
+-----------+
| arr |
+-----------+ +------------+
| reference |------>| MyObject[] |
+-----------+ +------------+
| null |
| null |
| null |
| (96 more) |
| null |
+------------+
Then you assign an instance, say:
arr[1] = new MyObject();
That gives you
+-----------+
| arr |
+-----------+ +------------+
| reference |------>| MyObject[] |
+-----------+ +------------+
| null | +-------------------+
| reference |---->| MyObject instance |
| null | +-------------------+
| (96 more) | | someField |
| null | | someOtherField |
+------------+ | ... |
+-------------------+
...then maybe you add another:
+-----------+
| arr |
+-----------+ +------------+
| reference |------>| MyObject[] |
+-----------+ +------------+
| null | +-------------------+
| reference |---->| MyObject instance |
| reference |--+ +-------------------+
| (96 more) | | | someField |
| null | | | someOtherField |
+------------+ | | ... |
| +-------------------+
|
| +-------------------+
+->| MyObject instance |
+-------------------+
| someField |
| someOtherField |
| ... |
+-------------------+
...and so on as you store more instances in the array.