In Java, a LinkedList
is a doubly-linked list, meaning each element is stored in a node object like this:
class Node<E> {
E item;
Node<E> next;
Node<E> prev;
}
So every time you call add()
, the list creates a new Node
object to hold the element.
💾 Memory allocated per add()
:
Let’s break down what memory is needed for each new node:
1. The node object itself
- 1 object header: ~12–16 bytes
- 3 references (
item
,next
,prev
): ~4–8 bytes each (depending on JVM architecture) → Total: ~24 to 32 bytes for the node (just for links and metadata)
2. The element itself
- If it’s a primitive wrapper like
Integer
, the element is also heap-allocatedInteger
= object header +int
value → ~16 bytes
- If it’s a reference to an existing object, only a reference is stored — no new object is created.
🔢 Approximate total per element:
Element Type | Memory Added (Approx) |
---|---|
Integer (boxed) | 🔺 Node (~24–32 B) + 🔺 Integer (~16 B) = ~40–50 bytes per element |
Object reference | 🔺 Node (~24–32 B) + ↔ shared object |
Compare this to ArrayList
, which just stores a reference → ~4–8 bytes per element (much lighter!).
🧠 Summary:
Structure | Per Element Overhead |
---|---|
ArrayList | ✅ ~4–8 bytes (just a reference) |
LinkedList | ❌ ~24–32 bytes (for node) + optional object |
int[] | ✅ 4 bytes (value stored directly) |
💡 So in short:
Calling linkedList.add(x)
allocates:
- A new Node object (24–32 bytes)
- Possibly a new object for
x
(if it’s a boxed primitive likeInteger
)
So it’s much heavier on memory than ArrayList
.