Explain Codes LogoExplain Codes Logo

Initial size for the ArrayList

java
arraylist
list-initialization
index-out-of-bounds
Nikita BarsukovbyNikita Barsukov·Dec 31, 2024
TLDR

For optimized performance, initialize an ArrayList with known capacity. This minimizes dynamic array resizing.

ArrayList<String> list = new ArrayList<>(100); // Console: "Room for 100, coming up!"

Predetermining capacity reduces memory reallocation, which is a key to peak performance for large lists. Note that the initial capacity isn't meant to create usable slots but to reserve memory for future elements.

Capacity vs. Size: Don't get Confused

Understanding the difference between an ArrayList's capacity and its size is crucial. Capacity is the length of the underlying array, while size (obtained from size()) is the current number of elements that have been added.

Managing Elements: Adding and Modifying

Adding elements at specific positions? Make sure these indices are within the current size of the list. Using the add(int index, Object element) in a way that goes beyond the ArrayList's current size, you'll get a surprise from IndexOutOfBoundsException.

list.add(50, "Hello StackOverflow"); // Console: "Back off! Too far. 😅" => Error if list size < 50

But if the ArrayList is already populated to a certain size, the set() method will modify elements at specific indices without a hitch.

Efficient ArrayList Initialization

If you need to initialize your list with repeated values or a set amount of pre-known elements - you got options:

  • Arrays.asList() - Use this for a fixed number of known elements.
List<String> fixedList = Arrays.asList("one", "two", "three"); // Console: "I got fixed size, don't try to squeeze more."
  • Collections.nCopies() - Use it to efficiently initialize an ArrayList with repeated values.
List<String> initializedList = new ArrayList<>(Collections.nCopies(100, "default")); // Console: "Pre-filled with 100 default values. No creativity here!"

Beyond ArrayList: Array, LinkedList and Fixed Size Lists

There may be times when ArrayList might not be your best tool to handle the job:

LinkedList and arrays

  • LinkedList, unlike ArrayList, chain-creates entries instead of resizing an array. It's your go-to when there's a lot of add/remove operations in the middle.
LinkedList<String> linkedList = new LinkedList<>();
  • Working with data that requires direct index access and won't resize? A standard array might be a better choice there.

Fixed-size lists

  • Want a list that changes together with an array? Arrays.asList() creates a fixed-size list that is backed by an array.
List<String> fixedList = Arrays.asList("fixed", "size", "list"); // Console: "Don't mess with my size!"