Explain Codes LogoExplain Codes Logo

How can I create an Array of ArrayLists?

java
arraylist
generics
type-safety
Alex KataevbyAlex Kataev·Nov 21, 2024
TLDR
ArrayList<Integer>[] arrayOfArrayLists = new ArrayList[10]; // New way to initialize array in Java 8, because why not! Arrays.setAll(arrayOfArrayLists, i -> new ArrayList<>());

This creates and initializes an array of 10 ArrayList<Integer> objects.

Creating an Array of ArrayLists

You may intend to create an array with generics like new ArrayList<Integer>[10], however, due to type erasure in Java and its prohibition of generic array creation, this will not compile. As a safer alternative, you can use a List of Lists:

List<List<Integer>> listOfLists = new ArrayList<>();

This maintains type safety by properly handling generics and bypassing issues specific to arrays of parameterized types. If you absolutely need an array of ArrayLists, use the following:

// Suppress trivial warnings so we can focus on the big ones @SuppressWarnings("unchecked") ArrayList<Integer>[] arrayOfLists = (ArrayList<Integer>[]) new ArrayList[10];

Reminder: Don't forget to initialize the ArrayList objects in the array:

for (int i = 0; i < arrayOfLists.length; i++) { // Look, ma, I'm making objects! arrayOfLists[i] = new ArrayList<>(); }

Flexibility with Collection Classes

Instead of using the ArrayList class directly, use the List interface for better flexibility and abstraction. This allows you to effortlessly swap to different concrete implementation later on.

List<List<String>> bookGenres = new ArrayList<>();

Customized ArrayList Creation

For advanced manipulation, create a custom class extending ArrayList. This is an effective way to encapsulate array creation logic while complying with the DRY (Don't Repeat Yourself) principle:

public class MyArrayList<T> extends ArrayList<T> { // More power to ArrayLists! } MyArrayList<Integer>[] myCustomArrays = (MyArrayList<Integer>[])new MyArrayList[10];

Explicit Casting with Wildcards

Sometimes, it's essential to accommodate arrays that handle wildcard types. In such cases, you can handle them like so:

ArrayList<?>[] wildCardArray = new ArrayList<?>[10];

However, individual elements will need to be explicitly cast to their actual type during use.

Living with Primitives

Java provides wrapper classes such as Integer, Double, etc. to store lists of primitives:

List<List<Integer>> scores = new ArrayList<>();

Null Elements

Before accessing objects, always check for null to avoid invoking the wrath of the NullPointerException.

if (arrayOfArrayLists[i] != null) { // Phew, it exists! }

Performance Advice

Compared to arrays, ArrayLists offer dynamic resizing, which can be a performance boon if your data size is unpredictable. So, using ArrayList of ArrayList can improve performance for frequent insertions and deletions.