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 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.

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)