How can I create an Array of ArrayLists?
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:
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:
Reminder: Don't forget to initialize the ArrayList
objects in the array:
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.
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:
Explicit Casting with Wildcards
Sometimes, it's essential to accommodate arrays that handle wildcard types. In such cases, you can handle them like so:
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:
Null Elements
Before accessing objects, always check for null to avoid invoking the wrath of the NullPointerException
.
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.
Was this article helpful?