
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Last updated: December 14, 2024
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:
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.
We can create an empty ArrayList instance using the no-arg constructor:
List<String> list = new ArrayList<>();
assertTrue(list.isEmpty());
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);
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));
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));
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.
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);
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);
}
}
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.
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.
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.
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.
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).
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.
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.