← 输入框|www.baeldung.com|刷新
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 – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

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

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW