Java ArrayList Examples

1. Introduction

The ArrayList in Java is one of the most used classes in the JDK. It is an implementation of a resizable array with a range of useful methods for manipulating the array. In this article, we present some of the usage patterns of the ArrayList.

The ArrayList is a concrete implementation of the List interface. As such, it is fine to refer to List instead of ArrayList when the implementation detail does not matter. The examples below use List instead of ArrayList when this difference is not relevant.

2. Array vs ArrayList

A regular array in java is a container which holds a fixed number of elements of a specific type. The following (stringArray) is a declaration of an array of String objects and is initialized to an array enough to store 20 strings.

String[] stringArray = new String[20];

An ArrayList for storing Strings is defined as shown below. The number 20 is an indication to the ArrayList class to reserve enough space for 20 strings.

ArrayList<String> stringList = new ArrayList<String>(20);

Some of the differences between the two:

  • Addition: The stringArray can store upto 20 strings. If you need to store more later on, you will have to re-initialize the array and copy the contents from the old array. With the ArrayList, you can add more than 20 strings without worrying about the capacity.
  • Removal: With the ArrayList it is easy to remove entries, either at a particular index or a range or a particular object. Not so easy with the array. You will need loops and other boiler-plate code to manage the removal in your code.

3. Creating an ArrayList

As already shown above you can create an ArrayList using the constructor. To create an empty ArrayList with a capacity for 10 Objects:

ArrayList<Object> objArray = new ArrayList<>();

To create an ArrayList from another Collection such as a Set or a List, you can use:

Set<String> stringSet = ..;
List<String> list = new ArrayList<String>(stringSet);

What if you need to create a List from a bunch of objects already lying around in your code? You can use Arrays.asList() as follows:

List<String> list = Arrays.asList("Apple", "Banana", "Orange");

The following selects lines from a text file using Java 8 streams.

List<String> lines = Files
    .lines(Paths.get(textFile))
    .filter(x -> x.length() > 50)
    .collect(Collectors.toList());

4. Convert Array to ArrayList

As presented above, it is simple to convert to a List if you have a plain array of objects.

List<String> a = Arrays.asList(args);

The above is suitable if you have an array of objects. What if you have an array of a primitive type, say an int? Here is how you can handle that case.

int[] array = { 2, 4, 5 };
List<Integer> list = Arrays
    .stream(array)
    .boxed()
    .collect(Collectors.toList());

5. Convert ArrayList to Array

The List interface provides a method toArray() which creates and returns a new array containing all the elements in the ArrayList.

List<String> strList = ...;
String[] strArray = strList.toArray();

6. Add to ArrayList

Use the method add() to add items to a List. This invocation adds elements at the end of the list.

List<String> strList = new ArrayList<>();
strList.add("Apple");
strList.add("Banana");
strList.add("Orange");
strList.stream().forEach(System.out::println);

// prints
Apple
Banana
Orange

To add all elements of a collection, use addAll().

List<String> modList = new ArrayList<>();
modList.addAll(strList);
modList.add("Melon");

7. UnsupportedOperationException

The following code results in an UnsupportedOperationException. The reason is than Arrays.asList() returns a fixed sized list backed by the input array. So you cannot add elements to the List returned by Arrays.asList().

A simple solution is to create a new ArrayList from the original list as follows:

List<String> strList = Arrays.asList("Apple", "Banana", "Orange");
List<String> modList = new ArrayList<>(strList);
modList.add("Melon");

Or you could use Java 8 streams:

List<String> modList = strList
	.stream()
	.collect(Collectors.toList());
modList.add("Melon");
modList.stream().forEach(System.out::println);

// prints:
Apple
Banana
Orange
Melon

8. Remove from ArrayList

Removal of items from a List is also easy. Remove an element at a particular index.

List<String> modList = new ArrayList<>();
modList.addAll(strList);
modList.add("Melon");
modList.remove(2);

// contains:
Apple
Banana
Melon

Remove a particular object as shown below. Note: The equals() method is used for checking whether to remove the object. It works as shown for String. For another class, equals() might be defined in terms of memory addresses, in which case the same object instance must be passed in to remove it.

List<String> modList = new ArrayList<>();
modList.addAll(strList);
modList.add("Melon");
modList.remove("Orange");

// contains
Apple
Banana
Melon

What if you want to remove an object with some specific characteristic. Use the removeIf() method with the predicate. The methods removes all elements that match the predicate.

List<String> modList = new ArrayList<>();
modList.addAll(strList);
modList.add("Melon");
modList.removeIf(x -> x.endsWith("e"));

// contains
Banana
Melon

Remove all objects from one List that are found in another List using removeAll().

List<String> modList = new ArrayList<>();
modList.addAll(strList);
modList.add("Melon");
modList.removeAll(Arrays.asList("Banana", "Kiwi"));

// contains
Apple
Orange
Melon

Summary

This article explained Java arrays and ArrayList from the perspective of a beginner. We showed creation and initialization of ArrayList. The ArrayList provides a bunch of methods to add and remove elements from the list. In some cases, the List created may not be modifiable in which case an exception is thrown when you try to modify it.