Explain Codes LogoExplain Codes Logo

Add object to ArrayList at specified index

java
indexoutofbounds
best-practices
collections
Anton ShumikhinbyAnton Shumikhin·Jan 28, 2025
TLDR

You can quickly insert an object into an ArrayList at a specific position using the list.add(index, element) method. This action moves the rest of the elements to the right. However, beware of the IndexOutOfBoundsException when the index exceeds the list size.

ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "C")); list.add(1, "B"); // The List morphs into [A, B, C]...magic!

Combatting IndexOutOfBoundsException

Before you run list.add(index, element), check that your index is within bounds. This prevents the dreaded IndexOutOfBoundsException. If it's necessary, increase the ArrayList's capacity beforehand. Safety first, as they say!

if(index >= 0 && index <= list.size()) { list.add(index, element); // You have successfully added an element. Let's celebrate... quietly. } else { System.out.println("Index " + index + " is out of bounds for list of size " + list.size()+ ". Learn to count!"); }

Enter HashMap: A valid alternative

When adding objects out of sequence, consider using a HashMap<Integer, Object>. Your HashMap's key becomes the desired index, side-stepping potential index issues, thus giving our Arraylist some breathing room.

HashMap<Integer, String> map = new HashMap<>(); map.put(5, "E"); // Adding "E" at position 5, because why not?

You can later form an ArrayList based on the keys, by sorting the HashMap and slurping it into an ArrayList.

Arrays: When to use them

Consider an array if you want to set elements at specific indices without invoking the shift operation, the gift/curse of the ArrayList.

String[] array = new String[5]; array[2] = "C"; // Directly assigning "C" to index 2. Who's the boss? You are!

Convert the arrays into an ArrayList using Arrays.asList() if dynamic resizing or more collection operations are needed, thus saving your sanity.

Custom ArrayList: A possible solution

For complex scenarios, a hero rises in the form of a custom ArrayList. This brave class can insert nulls when the specified index is larger than its current size, bypassing the IndexOutOfBoundsException and allowing additions at any index.

public class CustomArrayList<T> extends ArrayList<T> { @Override public void add(int index, T element) { while(index >= size()) { super.add(null); // "Fear no IndexOutOfBoundsException!", cried the knight, filling nulls up to the index } super.set(index, element); // Successfully setting the element at the index. A true Maestro! } }

Efficient additions: A series of patterns

When adding multiple elements at different indices, consider the following efficient strategies to reduce the overhead.

  • Bulk operations: Lump your insertions together. It will thank you for it by reducing the number of shifts.
  • Descending order: Start from the last index down when inserting multiple objects. Your reward? Fewer shifts.
  • Pre-sized list: Initiate the ArrayList with a capacity that can handle the expected additions. It saves on resizing costs.

Traps to avoid

Study the documentation of ArrayList.add thoroughly to understand its usage and edge cases. Be vigilant about:

  • Inserting at index zero: The element will be added at the front, pushing everything else to the right.
  • List end: Adding at list.size() will append your object without invoking the dreaded shifting.
  • Concurrent issue: Be aware of potential problems with multi-threaded access. Make sure your operations are thread-safe to prevent your program from unintentionally creating art.