Course contentsShow
← Java
Lesson 1003 of 2,87024. List ImplementationsFree lesson

Specifying Initial Capacity Explicitly

Learn how to set initial capacity with ArrayList(int) and when this optimization matters.

Specifying Initial Capacity Explicitly

You'll learn how to optimize ArrayList creation by setting its initial capacity and when this actually matters.

The Core Idea

When you create an ArrayList, you can tell it exactly how many elements you expect to store by using the constructor ArrayList(int initialCapacity). This pre-allocates space in the backing array, avoiding the cost of resizing as elements are added.

Think of it like reserving restaurant tables: if you know 50 guests are coming, you tell the restaurant ahead of time rather than starting with 2 tables and constantly asking for more.

When This Optimization Matters

Remember that ArrayList uses a dynamic array that grows automatically? Each time it grows, Java must:

  1. Create a new, larger array
  2. Copy all existing elements to the new array
  3. Discard the old array

If you know you'll be adding approximately 1,000 elements, specifying that capacity upfront eliminates these expensive resize operations:

// Default capacity (10) - will resize multiple times for 1,000 elements
ArrayList<String> names = new ArrayList<>();

// Pre-sized for 1,000 elements - no resizing needed
ArrayList<String> namesOptimized = new ArrayList<>(1000);

When It Doesn't Matter

For small collections (under 100 elements) or when you genuinely don't know the size, skip this optimization. Premature optimization adds complexity without meaningful benefit. The default constructor works perfectly fine for most everyday use cases.

Key Takeaway: Use ArrayList(int initialCapacity) when you know approximately how many elements you'll store AND that number is large enough to cause multiple resizes—otherwise, stick with the simple default constructor.