Skip to content
JackSparrow414
Go back

Observations on ArrayList Capacity Growth

Table of contents

Open Table of contents

Article body

Yesterday I ran into an ArrayList issue. It involved something basic that I hadn’t paid attention to in everyday coding.

The problem:

 I used an ArrayList to collect the model from each iteration of a loop with a fixed count of 12. After running it, I saw what appeared to be 15 models in the list, with the last three null, even though the loop had run only 12 times. I was puzzled.

Investigating the issue:

After debugging a few times, I thought I had found the answer: ArrayList’s initial capacity. I believed it was 15, which would explain why adding 12 entries left three null values. I set the initial capacity to 12 and the issue appeared resolved. However, that explanation was wrong.

Looking more closely:

When I opened ArrayList’s definition, I realized how mistaken I had been. Its initial capacity is actually 10, and when that capacity is exceeded, it grows to 1.5 times the current capacity. In the account recorded here, the first expansion therefore gives a capacity of 16.

What I learned:

I had memorized plenty of Java fundamentals but hadn’t paid attention to them in actual development. In future, I need to focus on more than just speed: careful, attentive coding is how we reduce bugs.

When the expected collection size is known, specify an initial capacity.

------------------Sometimes a stumble makes the lesson stick-------Remember that--------------

Here is an additional screenshot:

Explanation of elementData, size, and capacity growth in ArrayList


Share this post:

Previous Post
Java Development Details (Part 2): Configuration Mistakes
Next Post
Understanding Spring MVC through a Request-Mapping Error

Comments

Questions, corrections, and experiences are welcome. Sign in with GitHub to comment; both language versions share this discussion.

Comments are available on the live site only.