Does oneElmCatArray
take up the same amount of memory as aSingleCat
, or does it take up more because of some behind-the-scenes Java array shenanigans?
The answer is: it depends.
First of all, it is important1 that you understand what a Cat[]
actually contains.
- It does not contain
Cat
objects.
- It actually contains either references to
Cat
objects, OR null
references.
In each case, a reference will occupy either 4 or 8 bytes depending on the JVM platform and (in some cases) the command line options.
So, does a Cat
occupy more memory than a Cat[1]
? The answer will actually depend on:
- The size of a reference (see above)
- The number and type of the instance fields of the
Cat
class ... which is unspecified in your question.
When doing the actual calculations, you need to include the sizes of the respective native object / array headers (8 and 12 bytes respectively). Also, take account of the fact that JVM heap node sizes are a multiple of 8 bytes. (But these things are in theory implementation dependent.)
Finally, as @Louis Wasserman points out, the answer also depends on your "accounting" rules. When Cat[]
contains a reference to a Cat
, do you count the Cat
as part of the array or not?
1 - If you don't understand this, you are going to end up with an incorrect mental model of arrays and how they work. That is likely to lead to bugs in your code.