null与空ArrayList<String>哪个占用内存空间更多?
ArrayList<String>: Memory Comparison Great question—this is a common point of confusion when reasoning about Java memory usage, so let’s break it down clearly:
First: What’s the memory cost of null?
In Java, null is a value that a reference variable can hold to indicate it doesn’t point to any object. The size of this reference depends on your JVM and system architecture:
- On 32-bit JVMs: 4 bytes per reference
- On 64-bit JVMs: 8 bytes by default, or 4 bytes if compressed pointers (enabled by default in most modern JVMs for heaps under 32GB) are turned on.
Crucially: null doesn’t allocate any object memory—it’s just a marker value in the reference variable itself.
Next: Memory cost of an empty ArrayList<String>
An empty ArrayList is a full Java object, with its own memory footprint. Let’s break down what makes up its size (using HotSpot JVM as an example, since it’s the most common):
Object Header: Every Java object has a header containing metadata (Mark Word for locking/hashing, Klass Pointer to the class definition).
- With compressed pointers (64-bit): 12 bytes
- Without compressed pointers (64-bit): 16 bytes
- 32-bit JVM: 8 bytes
Instance Variables:
ArrayListhas three core instance variables:elementData: A reference to the underlying array (holds the list elements). For an emptyArrayList, this points to a shared static empty array (EMPTY_ELEMENTDATA), so we don’t count the array’s memory here (it’s reused across all empty instances).size: Anint(4 bytes) tracking the number of elements (0 for empty).modCount: Anint(4 bytes) for fail-fast iterator checks.
Memory Alignment: Java objects are padded to the nearest multiple of 8 bytes to optimize memory access.
Putting this together for common scenarios:
- 64-bit with compressed pointers: 12 (header) + 4 (elementData) + 4 (size) + 4 (modCount) = 24 bytes (already aligned to 8)
- 64-bit without compressed pointers: 16 (header) + 8 (elementData) + 4 + 4 = 32 bytes (aligned)
- 32-bit JVM: 8 (header) +4+4+4=20 → padded to 24 bytes
The Bottom Line
- A
nullreference only uses the size of the reference variable (4 or 8 bytes) and no additional object memory. - An empty
ArrayList<String>uses that same reference size (for the variable pointing to it) plus 24–32 bytes for theArrayListobject itself.
So the empty ArrayList takes significantly more memory than a null reference.
内容的提问来源于stack exchange,提问作者jpganz18

