eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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. Handy Utility Methods to Obtain a List

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. Next, let’s see a few of them.

4.1. Collections.singletonList()

When we need a List containing exactly one element, Java provides a handy utility method: Collections.singletonList(). We don’t have to create a new ArrayList and add an item manually. Instead, we can quickly wrap a single object into an immutable List. This is especially useful when we want to pass a one‑element list to APIs that expect a List.

Next, let’s look at an example:

List<Passenger> singletonList = Collections.singletonList(passenger1);

assertThat(singletonList).hasSize(1);
assertThat(singletonList.get(0)).isEqualTo(passenger1);
assertThrows(UnsupportedOperationException.class, () -> singletonList.add(passenger2));

As we can see, Collections.singletonList() is pretty handy to create a one-element immutable List.

4.2. Collections.unmodifiablelist()

Sometimes we want to share a List with other parts of our code, but ensure that no one can modify it. For this, we can wrap an existing List with Collections.unmodifiableList(). What we get is a read-only view of the original List. We can still read elements, but any attempt to add, remove, or update will throw an exception. This is useful when we want to protect data integrity while still allowing access.

List<Passenger> originalList = new ArrayList<>();
originalList.add(passenger1);
originalList.add(passenger2);

List<Passenger> unmodifiableList = Collections.unmodifiableList(originalList);
assertThat(unmodifiableList).isEqualTo(originalList);

assertThrows(UnsupportedOperationException.class, () -> unmodifiableList.add(passenger3));
assertThrows(UnsupportedOperationException.class, () -> unmodifiableList.remove(passenger2));

So, this approach is convenient for creating a read-only view of a List. It’s worth mentioning that since this is a read-only view of the original List, it reflects the changes made to the underlying List:

originalList.add(passenger3);
assertThat(unmodifiableList).hasSize(3);

As we can see, the unmodifiableList view reflects the changes we made to orginalList,

4.3. Arrays.asList()

When we want to convert an array into a List quickly, we can use Arrays.asList(). This method wraps the array into a fixed-size List backed by the original array. We can read and update elements through the list, but we cannot change its size (no adding or removing).

Next, let’s understand its usage through an example:

Passenger[] array = { passenger1, passenger2 };
List<Passenger> list = Arrays.asList(array);

assertThat(list).hasSize(2);
assertThat(list.get(0)).isEqualTo(passenger1);
assertThat(list.get(1)).isEqualTo(passenger2);

// We can update elements (reflected in the array too)
list.set(1, passenger3);
assertThat(array[1]).isEqualTo(passenger3);

// Verify immutability of size: adding/removing throws UnsupportedOperationException
assertThrows(UnsupportedOperationException.class, () -> list.add(passenger2));
assertThrows(UnsupportedOperationException.class, () -> list.remove(passenger1));

As the example shows, Arrays.asList() makes it a convenient way to work with arrays using the List API.

4.4. Arrays.subList()

Sometimes we want to work with just a portion of a List, we can use the subList(fromIndex, toIndex) method. It gives us a view of the original List between the specified indices. We can read and modify elements in the sublist, and those changes are reflected in the original List:

List<Passenger> originalList = Arrays.asList(passenger1, passenger2, passenger3, passenger4, passenger5);
List<Passenger> subList = originalList.subList(1, 3);

assertThat(subList).isEqualTo(Arrays.asList(passenger2, passenger3));

// Changes in sublist reflect in the original list
subList.set(1, passenger6);
assertThat(originalList.get(2)).isEqualTo(passenger6);

// immutability of size: adding/removing throws UnsupportedOperationException
assertThrows(UnsupportedOperationException.class, () -> subList.add(passenger4));
assertThrows(UnsupportedOperationException.class, () -> subList.remove(passenger2));

As we can see, we cannot perform add or remove operations on subList.

4.5. List.of()

Starting with Java 9, we can easily create immutable Lists using List.of(). Unlike Arrays.asList(), which produces a fixed-size list backed by an array, List.of() creates a truly unmodifiable List. We can’t add, remove, or change elements, and it doesn’t reflect changes from any underlying array.

Next, let’s see how to use this method by an example:

List<Passenger> list = List.of(passenger1, passenger2, passenger3);

assertThat(list).isEqualTo(Arrays.asList(passenger1, passenger2, passenger3));

assertThrows(UnsupportedOperationException.class, () -> list.add(passenger4));
assertThrows(UnsupportedOperationException.class, () -> list.set(0, passenger4));
assertThrows(UnsupportedOperationException.class, () -> list.remove(passenger2));

List.of() makes it perfect when we want a concise, safe way to define constant lists.

4.6. List.copyOf()

Introduced in Java 10, List.copyOf() allows us to create an immutable copy of an existing collection. Unlike Collections.unmodifiableList(), which provides a read-only view that still reflects changes to the original List, List.copyOf() produces a true snapshot that cannot be modified and remains unchanged even if the source List changes.

As always, let’s understand this through examples:

List<Passenger> originalList = new ArrayList<>();
originalList.add(passenger1);
originalList.add(passenger2);
originalList.add(passenger3);

List<Passenger> copy = List.copyOf(originalList);

assertThat(copy).isEqualTo(originalList);

assertThrows(UnsupportedOperationException.class, () -> copy.add(passenger4));
assertThrows(UnsupportedOperationException.class, () -> copy.set(0, passenger4));
assertThrows(UnsupportedOperationException.class, () -> copy.remove(passenger2));

// Changes to the original list do NOT affect the copy
originalList.add(passenger6);
assertThat(copy).hasSize(3);

As we can see, List.copyOf() is ideal when we want a safe, independent copy of data.

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.

Also, we explored some convenient utility methods that return an abstract List type provided by the Java standard library.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)