Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this article, we’ll look into the differences between using the List and ArrayList types.

First, we’ll see a sample implementation using ArrayList. Then, we’ll switch to the List interface and compare the differences.

2. Using ArrayList

ArrayList is one of the most commonly used List implementations in Java. It’s built on top of an array, which can dynamically grow and shrink as we add/remove elements. It’s good to initialize a list with an initial capacity when we know that it will get large:

ArrayList<String> list = new ArrayList<>(25);

By using ArrayList as a reference type, we can use methods in the ArrayList API that are not in the List API — for example, ensureCapacity, trimToSize, or removeRange.

2.1. Quick Example

Let’s write a basic passenger processing application:

public class ArrayListDemo {
    private ArrayList<Passenger> passengers = new ArrayList<>(20);

    public ArrayList<Passenger> addPassenger(Passenger passenger) {
        passengers.add(passenger);
        return passengers;
    }
    
    public ArrayList<Passenger> getPassengersBySource(String source) {
        return new ArrayList<Passenger>(passengers.stream()
            .filter(it -> it.getSource().equals(source))
            .collect(Collectors.toList()));
    }
    
    // Few other functions to remove passenger, get by destination, ... 
}

Here, we’ve used the ArrayList type to store and return the list of passengers. Since the maximum number of passengers is 20, the initial capacity for the list is set to this.

2.2. The Problem with Variable Sized Data

The above implementation works fine so long as we don’t need to change the type of List we’re using. In our example, we chose ArrayList and felt it met our needs.

However, let’s assume that as the application matures, it becomes clear that the number of passengers varies quite a lot. For instance, if there are only five booked passengers, with an initial capacity of 20, the memory wastage is 75%. Let’s say we decide to switch to a more memory-efficient List.

2.3. Changing the Implementation Type

Java provides another List implementation called LinkedList to store variable-sized data. LinkedList uses a collection of linked nodes to store and retrieve elements. What if we decided to change the base implementation from ArrayList to LinkedList:

private LinkedList<Passenger> passengers = new LinkedList<>();

This change affects more parts of the application because all the functions in the demo application expect to work with the ArrayList type.

3. Switching to List

Let’s see how can we handle this situation by using the List interface type:

private List<Passenger> passengers = new ArrayList<>(20);

Here, we’re using the List interface as the reference type instead of the more specific ArrayList type. We can apply the same principle to all the function calls and return types. For example:

public List<Passenger> getPassengersBySource(String source) {
    return passengers.stream()
        .filter(it -> it.getSource().equals(source))
        .collect(Collectors.toList());
}

Now, let’s consider the same problem statement and change the base implementation to the LinkedList type. Both the ArrayList and LinkedList classes are implementations of the List interface. So, we can now safely change the base implementation without creating any disturbances to other parts of the application. The class still compiles and works fine as before.

4. Comparing the Approaches

If we use a concrete list type throughout the program, then all of our code is coupled with that list type unnecessarily. This makes it harder to change list types in the future.

In addition, the utility classes available in Java return the abstract type rather than the concrete type. For instance, utility functions below return the List type:

Collections.singletonList(...), Collections.unmodifiableList(...)
Arrays.asList(...), ArrayList.sublist(...)

Specifically, ArrayList.sublist returns the List type, even though the original object is of ArrayList type. As such, methods in the List API don’t guarantee to return a list of the same type.

5. Conclusion

In this article, we examined the differences and best practices of using List vs ArrayList types.

We saw how referencing a specific type can make the application vulnerable to change at a later point in time. Specifically, when the underlying implementation changes, it affects other layers of the application. Hence, using the most abstract type (top-level class/interface) is often preferred over using a specific reference type.

As always, the source code for the examples is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.