How do I use ArrayList class?

In this example we will learn how to use the java.util.ArrayList class. An ArrayList is part of the Java Collection Framework. By using this class we can create a dynamic size array of data, which means we can add or remove elements from the array dynamically.

In the code below we will see the demonstration on how to create an instance of ArrayList, add some elements, remove elements and iterate through the entire ArrayList elements either using a for-loop or using the for-each syntax.

We can also see how to convert the ArrayList into an array object using the toArray() method. And we use the Arrays.toString() utility method when we want to print the content of an array.

When creating a class instance it is a good practice to use the interface as the type of variable instead of the concrete type directly. This can make us easily update our code if we don’t want to use ArrayList in the future.

And here is the code snippet:

package org.kodejava.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        // Add items into ArrayList
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");

        // Remove the third item from ArrayList, first index = 0
        list.remove(2);

        // Iterate ArrayList item using for loop statement
        for (int i = 0; i < list.size(); i++) {
            String item = list.get(i);
            System.out.println("Item = " + item);
        }

        // Iterate ArrayList item using enhanced for statement
        for (String item : list) {
            System.out.println("Item = " + item);
        }

        // Iterate ArrayList item using forEach
        list.stream().map(item -> "Item = " + item).forEach(System.out::println);

        // Convert ArrayList into array of object
        String[] array = list.toArray(new String[0]);
        System.out.println("Items = " + Arrays.toString(array));
    }
}

Executing the program will give us the following output printed in our console.

Item = Item 1
Item = Item 2
Item = Item 1
Item = Item 2
Item = Item 1
Item = Item 2
Items = [Item 1, Item 2]
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.