ArrayList capacity growth — if Capacity is 4, what is the capacity after adding the 5th element?

Difficulty: Easy

Correct Answer: 8

Explanation:


Introduction / Context:
ArrayList grows its internal storage automatically. Understanding capacity growth helps explain amortized insertion costs.



Given Data / Assumptions:

  • Initial Capacity property is 4.
  • A 5th element is added, exceeding current capacity.


Concept / Approach:
ArrayList uses a dynamic array. When capacity is exceeded, it increases capacity (commonly doubling) to accommodate additional items, reducing the frequency of reallocations.



Step-by-Step Solution:

Attempt to add element number 5 to capacity 4.ArrayList resizes underlying array, typically doubling from 4 to 8.Capacity becomes 8; Count becomes 5.


Verification / Alternative check:
Write a short program that sets Capacity to 4, adds 5 items, and prints Capacity and Count.



Why Other Options Are Wrong:
4 is impossible (insufficient for 5 items); 16 and 32 are too large for a single resize; element type does not affect capacity growth.



Common Pitfalls:
Confusing Capacity (allocated slots) with Count (actual elements).



Final Answer:
8

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion