An Overview of Java ArrayList

Posted By : Dhiraj Chauhan | 31-Oct-2022

Java

Loading...

1. Introduction

In this blog, we aregoing to deep diveinto theArrayListclass from the Java Collections Framework. Our discussion will cover its properties, common use cases, and advantages and disadvantages.

ArrayListexists within Java Core Libraries, so you don't need any additional libraries for this. In order to use ArrayList just add the following import statement:

import java.util.ArrayList;

A list represents an ordered sequence of values and it can contain duplicate values.

ArrayListis one of theListimplementations built atop an array, which can dynamically grow and shrink as you add or remove elements from it. This implementation has the following properties:

  • Random access takesO(1)time
  • Adding an element takes amortized constant timeO(1)
  • Inserting/Deleting takesO(n)time
  • Searching time takenO(n)for an unsorted array andO(log n)for a sorted array.

2. Create anArrayList

ArrayListhas several constructors and we will present all of them in this section.

First, notice thatArrayListis a generic class, so you can parameterize it with any type of data you want and the compiler will understand that, for example, A collection of Strings cannot contain Integer values. In addition, you don't need to cast elements when retrieving them from a collection.

Secondly, it's agood practice to use a generic interfaceListas a variable type, because it de-coupleit from a particular implementation.

2.1. Default No-Arg Constructor

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

2.2. Constructor Accepting Initial Capacity

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

2.3. Constructor AcceptingCollection

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. Add Elements to theArrayList

Insert an element at the end or at a specific position:

List<Long> list = new ArrayList<>();
list.add(1L);
list.add(2L);
list.add(1, 3L);
assertThat(Arrays.asList(1L, 3L, 2L), equalTo(list));

It is also possible to insert a collection or several elements at once:

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, 0L, 2L, 3L), equalTo(list));

4. Iterate Over theArrayList

You can choose between two types of iterators: Iterator and ListIterator.

While the former offers you the possibility to traverse the listing in one direction, the latter permits you to traverse it in each direction.

Here we'llshow youtheListIterator:

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));

It is also possible to search, add or remove elements using iterators.

5. Search theArrayList

Using a collection, we will demonstrate how searching works:

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

In order to find an element you may useindexOf()orlastIndexOf()methods. Both accept an object and return anintvalue:

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

If you choose to discover all factors pleasant a predicate, you may filter collection the use of Java 8 Stream API (read more about it here) the usage of Predicate like this:

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());

You may also use aforloop 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

If you have a sorted array, then you may additionally use a binary search algorithm which works quicker 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 is now not discovered then -1 will be returned.

6. Remove Elements from theArrayList

In order to dispose of an element, you must locate its index and only then perform the removal by way of eliminate method. An overloaded model of this method, that accepts an object, searches for it and performs removal of the first occurrence of an equal element:

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));

In order to cast off a specific element, you must first box int value or otherwise, an issue will be removed by way of its index.

You can also as well use the aforementioned Stream API for disposing of quite a few items, but we might not exhibit it here. For this cause we will use an iterator:

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();
}
}

7. Summary

In this short blog, we had a detailed look at the ArrayList in Java.

We showed how to create anArrayListinstance and how to add, find or remove elements by different approaches.

We, at Oodles,provide end-to-endenterprise web app development serviceswith a focus on strengthening the web presence of enterprises and solving complex business problems. Our end-to-endERP application development servicesenable enterprises to streamline their operations and achieve higher levels of productivity. Contact us at [email protected] for more detail.