Skip to content

Commit 1a50222

Browse files
committed
Internal Working of ArrayList.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent b1a41a4 commit 1a50222

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
Internal Working of ArrayList:
2+
3+
Initial State (Default Capacity = 10)
4+
+----+----+----+----+----+----+----+----+----+----+
5+
| | | | | | | | | | |
6+
+----+----+----+----+----+----+----+----+----+----+
7+
Size = 0 Capacity = 10
8+
9+
Step 1: Add 10 elements → fills up the array
10+
+--1-+--2-+--3-+--4-+--5-+--6-+--7-+--8-+--9-+--10-+
11+
Size = 10 Capacity = 10
12+
13+
Step 2: Add 11th element → triggers resize
14+
New Capacity = (oldCapacity * 3) / 2 + 1 = 16
15+
+--1-+--2-+--3-+--4-+--5-+--6-+--7-+--8-+--9-+--10-+--11-+ ... (empty slots)
16+
Size = 11 Capacity = 16
17+
18+
Step 3: Keep adding elements
19+
When size > capacity, ArrayList creates a new array
20+
with larger capacity and copies old elements into it.
21+
22+
23+
24+
Step-by-Step Internal Process of add(element):
25+
1. Check if size < capacity.
26+
• If yes → place the element at index = size, increment size.
27+
• If no → resize happens.
28+
2. Resizing:
29+
• New capacity = (oldCapacity * 3) / 2 + 1 (approx 1.5x growth).
30+
• A new array is created with the new capacity.
31+
• Old elements are copied into the new array.
32+
• Add the new element.
33+
3. This process repeats as more elements are added.
34+
35+
36+
37+
⚡ Example:
38+
• Start with capacity = 10.
39+
• Add elements until 10 → full.
40+
• Add one more → new capacity = 16.
41+
• Add more → capacity grows: 16 → 25 → 38 → 57 …
42+
43+
This ensures ArrayList grows dynamically while balancing memory and performance.

0 commit comments

Comments
 (0)