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.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
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 – LambdaTest – NPI EA (cat=Testing)
announcement - icon

End-to-end testing is a very useful method to make sure that your application works as intended. This highlights issues in the overall functionality of the software, that the unit and integration test stages may miss.

Playwright is an easy-to-use, but powerful tool that automates end-to-end testing, and supports all modern browsers and platforms.

When coupled with LambdaTest (an AI-powered cloud-based test execution platform) it can be further scaled to run the Playwright scripts in parallel across 3000+ browser and device combinations:

>> Automated End-to-End Testing With Playwright

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

1. Overview

In this tutorial, we’ll look at the ArrayList class from the Java Collections Framework. We’ll discuss its properties, common use cases, and advantages and disadvantages.

ArrayList resides within Java Core Libraries; therefore, we don’t need additional libraries. To use it, we add its import statement:

import java.util.ArrayList;

The List represents an ordered sequence of values where a value can occur more than once.

ArrayList is a List implementation built atop an array that can dynamically grow and shrink as we add/remove elements. We can easily access an element by its index starting from zero. This implementation has the following properties:

  • Random access takes O(1) time
  • Adding an element takes amortized constant time O(1)
  • Inserting/Deleting takes O(n) time
  • Searching takes O(n) time for an unsorted array and O(log n) for a sorted one

2. Creating an ArrayList

Let’s introduce ArrayList constructors.

At the outset, ArrayList<E> is a generic class; therefore, we can parameterize it with any type we want. The compiler ensures that we can’t use a non-compatible type. For example, we can’t put Integer values inside a collection of Strings. Furthermore, we don’t need to cast elements when retrieving them from a collection.

We should use the generic interface List<E> as a variable type as a best practice because it decouples it from any specific implementation.

2.1. Default No-Arg Constructor

We can create an empty ArrayList instance using the no-arg constructor:

List<String> list = new ArrayList<>();
assertTrue(list.isEmpty());

2.2. Constructor Accepting Initial Capacity

We can specify the initial length of an underlying array to avoid unnecessary resizing while adding new items using the constructor that accepts initial capacity:

List<String> list = new ArrayList<>(20);

2.3. Constructor Accepting Collection

We can create a new ArrayList instance using elements of a Collection instance for populating the underlying array:

Collection<Integer> numbers 
  = IntStream.range(0, 10).boxed().collect(toSet());

List<Integer> list = new ArrayList<>(numbers);
assertEquals(10, list.size());
assertTrue(numbers.containsAll(list));

3. Adding Elements to the ArrayList

We can add an element either at the end or at a specific index position:

List<Long> list = new ArrayList<>();

list.add(1L);
list.add(2L);
list.add(1, 3L);

assertThat(Arrays.asList(1L, 3L, 2L), equalTo(list));

We can also add a collection or a batch of elements:

List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
LongStream.range(4, 10).boxed()
  .collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys)));
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list));

4. Iterating Over the ArrayList

We have two types of iterators available: Iterator and ListIterator.

We use an Iterator to traverse the list in one direction only and a ListIterator to traverse it in both directions.

Let’s use the ListIterator as an example:

List<Integer> list = new ArrayList<>(
  IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new))
);
ListIterator<Integer> it = list.listIterator(list.size());
List<Integer> result = new ArrayList<>(list.size());
while (it.hasPrevious()) {
    result.add(it.previous());
}

Collections.reverse(list);
assertThat(result, equalTo(list));

We can also search, add, or remove elements using iterators.

5. Searching the ArrayList

Let’s demonstrate searching using a collection:

List<String> list = LongStream.range(0, 16)
  .boxed()
  .map(Long::toHexString)
  .collect(toCollection(ArrayList::new));
List<String> stringsToSearch = new ArrayList<>(list);
stringsToSearch.addAll(list);

5.1. Searching an Unsorted List

We may use the indexOf() or the lastIndexOf() method to find an element. They both accept an object and return an int value:

assertEquals(10, stringsToSearch.indexOf("a"));
assertEquals(26, stringsToSearch.lastIndexOf("a"));

If we want to find all elements satisfying a predicate, we may filter collection using Java 8 Stream API using a Predicate:

Set<String> matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9"));

List<String> result = stringsToSearch
  .stream()
  .filter(matchingStrings::contains)
  .collect(toCollection(ArrayList::new));

assertEquals(6, result.size());

It is also possible to use a for loop or an iterator:

Iterator<String> it = stringsToSearch.iterator();
Set<String> matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9"));

List<String> result = new ArrayList<>();
while (it.hasNext()) {
    String s = it.next();
    if (matchingStrings.contains(s)) {
        result.add(s);
    }
}

5.2. Searching a Sorted List

To search a sorted array we may use a binary search algorithm, which works faster than linear search:

List<String> copy = new ArrayList<>(stringsToSearch);
Collections.sort(copy);
int index = Collections.binarySearch(copy, "f");
assertThat(index, not(equalTo(-1)));

Notice that if an element isn’t found then -1 is returned.

6. Removing Elements from the ArrayList

To remove an element, we find its index and then remove it using the remove() method. We can also use an overloaded version of this method, which accepts an object, searches for it, and removes its first occurrence:

List<Integer> list = new ArrayList<>(
  IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new))
);
Collections.reverse(list);

list.remove(0);
assertThat(list.get(0), equalTo(8));

list.remove(Integer.valueOf(0));
assertFalse(list.contains(0));

Let’s remember that when working with boxed types such as Integer, to remove a particular element, we should first box int value or otherwise, an element is removed by its index.

We can use an iterator to remove several items:

Set<String> matchingStrings
  = HashSet<>(Arrays.asList("a", "b", "c", "d", "e", "f"));

Iterator<String> it = stringsToSearch.iterator();
while (it.hasNext()) {
    if (matchingStrings.contains(it.next())) {
        it.remove();
    }
}

We may use the Stream API for removing several items, but we won’t show it here.

7. Using a Sequenced Collection – ArrayList

We can add, get, and remove the first or the last element in an ArrayList using a sequenced collection. Sequenced collections are introduced in Java 21 with the new java.util.SequencedCollection<E> interface. A sequenced collection has a well-defined encounter order for its elements. Accordingly, the elements have a linear arrangement: first element, second element, …, and last element. With java.util.Collection<E> as the root interface in the collection hierarchy, the java.util.SequencedCollection<E> extends it to provide a sequential arrangement for a collection’s elements.

The java.util.SequencedCollection<E> interface provides several methods for adding/getting/removing an element that’s either first or last in the sequence:

Method Description
addFirst(E e) Adds an element as the first element
addLast(E e) Adds an element as the last element
getFirst() Gets the first element
getLast() Gets the last element
removeFirst() Removes and returns the first element
removeLast() Removes and returns the last element

Let’s discuss with examples how to perform the add/get/remove operations on an ArrayList that’s a sequenced collection.

7.1. Getting First or Last Element

To get the first element, we call the instance method getFirst(). To demonstrate, let’s create an ArrayList:

ArrayList<Integer> arrayList = new ArrayList<Integer>(Arrays.asList(3,1,2));

We can use a JUnit 5 test with an assertEquals assertion to verify the first element returned:

@Test
public void givenSequencedArrayList_whenGetFirst_thenFirstElementReturnedCorrectly() {

    ArrayList arrayList = new ArrayList(Arrays.asList(3,1,2));

    Integer expectedElement=3;
    assertEquals(expectedElement, arrayList.getFirst());
}

The JUnit assertion test should pass. Similarly, to get the last element, we call the instance method getLast(). To demonstrate, let’s create an ArrayList as before. Again, we can use a JUnit 5 test to verify the last element returned:

@Test
public void givenSequencedArrayList_whenGetLast_thenLastElementReturnedCorrectly() {
       
    ArrayList arrayList = new ArrayList(Arrays.asList(3,1,2));

    Integer expectedElement=2;
    assertEquals(expectedElement, arrayList.getLast());
}

The JUnit assertion test should pass because the getLast() returns the last element.

7.2. Adding First or Last Element

To add a new first element in an existing collection, we call the instance method addFirst(E e). To demonstrate, let’s create an ArrayList, and add a new first element:

ArrayList<Integer> arrayList = new ArrayList<Integer>(Arrays.asList(3,1,2));
arrayList.addFirst(4);

We can use a JUnit 5 test with an assertEquals assertion to verify the first element added:

@Test
public void givenSequencedArrayList_whenAddFirst_thenFirstElementAddedCorrectly() {

    ArrayList arrayList = new ArrayList(Arrays.asList(3,1,2));
    arrayList.addFirst(4);
     
    Integer expectedElement=4;
    assertEquals(expectedElement, arrayList.getFirst());
}

Similarly, to add the last element to an existing collection, we call the instance method addLast(E e). Again, let’s create an ArrayList and use a JUnit 5 test to verify the last element added:

@Test
public void givenSequencedArrayList_whenAddLast_thenLastElementAddedCorrectly() {
       
    ArrayList arrayList = new ArrayList(Arrays.asList(3,1,2));
    arrayList.addLast(5);
    
    Integer expectedElement=5;
    assertEquals(expectedElement, arrayList.getLast());
}

The JUnit assertion test should pass because the getLast() returns the last element added with addLast(E e).

7.3. Removing First or Last Element

To remove the first element in an existing collection, we call the instance method removeFirst(). To demonstrate, let’s create an ArrayList and remove the first element. We can use a JUnit 5 test with an assertEquals assertion to verify the first element is removed:

@Test
public void givenSequencedArrayList_whenRemoveFirst_thenFirstElementRemovedCorrectly() {

    ArrayList arrayList = new ArrayList(Arrays.asList(3,1,2));
       
    Integer expectedElement=3;
    assertEquals(expectedElement, arrayList.removeFirst());
}

Similarly, to remove the last element in an existing collection, we call the instance method removeLast(). Let’s create an ArrayList and use a JUnit 5 test to verify the last element is removed:

@Test
public void givenSequencedArrayList_whenRemoveLast_thenLastElementRemovedCorrectly() {
       
    ArrayList arrayList = new ArrayList(Arrays.asList(3,1,2));
     
    Integer expectedElement=2;
    assertEquals(expectedElement, arrayList.removeLast());
} 

The JUnit assertion test should pass because the removeLast() returns the removed last element.

8. Summary

In this quick article, we had a look at the ArrayList in Java.

We showed how to create an ArrayList instance, and how to add, find, or remove elements using different approaches. Furthermore, we showed how to add, get, and remove the first, or the last element using sequenced collections introduced in Java 21.

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.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (All)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

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