🔍 The fields in ArrayList
:
transient Object[] elementData; // the actual data storage (may be larger than needed)
private int size; // the number of elements currently in the list
You’re asking:
Why store
size
separately, if we already haveelementData.length
?
Let’s break it down. 👇
✅ Because elementData.length
is the capacity, not the actual number of elements.
elementData.length
→ how many slots are allocated in the internal arraysize
→ how many real elements are stored in the list right now
They are not the same.
🧪 Example:
ArrayList<String> list = new ArrayList<>(10); // capacity = 10
list.add("A");
list.add("B");
elementData.length
= 10 (capacity)size
= 2 (actual elements)elementData[0] = "A"
elementData[1] = "B"
elementData[2]
toelementData[9]
=null
So if you used elementData.length
to determine the list size, you’d mistakenly think the list has 10 elements, when only 2 are real.
🚨 Why this matters:
- Iteration:
for (int i = 0; i < size; i++) {
process(elementData[i]);
}
- Avoiding nulls: if you go up to
elementData.length
, you’d hitnull
values - Correct behavior for
size()
,add()
,remove()
, etc.
🛠️ Analogy: A partially filled toolbox
elementData
= toolbox with 10 slotssize
= number of tools actually inside
You wouldn’t say the toolbox has 10 tools just because it has 10 slots!
📌 Summary
Property | What it means |
---|---|
elementData.length | Total capacity (allocated slots) |
size | Actual number of elements |
🔧
size
must be tracked separately to know which elements are real and avoid processingnull
s or uninitialized slots.