Java ArrayList Tutorial with Examples

Java ArrayList tutorial shows how to work with ArrayList collection with examples in Java. ArrayList is an important collection of the Java collections framework.
Learn and master Java Collections Framework at Learn Java Collections Framework
A collection is an object that represents a group of objects. A collections framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details.

Table of Contents

  • ArrayList Class Overview
  • ArrayList Class Diagram
  • ArrayList Class Methods
  • Example 1: Creating an ArrayList and Adding New Elements to It
  • Example 2: Example Demonstrates How the ArrayList Contains Duplicate and Null Values
  • Example 3: Creating an ArrayList From Another Collection
  • Example 4: Accessing Elements from an ArrayList
  • Example 5: Removing Elements from an ArrayList
  • Example 6: Iterating over an ArrayList
  • Example 7: Searching for Elements in an ArrayList
  • Example 8: ArrayList of User-Defined Objects
  • Example 9: Sorting an ArrayList
  • Example 10: Java List.of() API

ArrayList Class Overview

The ArrayList class is a resizable array, which can be found in the java.util package.

The important points about Java ArrayList class are:
  • Java ArrayList class can contain duplicate elements.
  • Java ArrayList class maintains insertion order.
  • Java ArrayList class is non-synchronized.
  • Java ArrayList allows random access because array works at the index basis.
  • In Java ArrayList class, manipulation is slow because a lot of shifting needs to have occurred if any element is removed from the array list.
  • You cannot create an ArrayList of primitive types like int, char, etc. You need to use boxed types like Integer, Character, Boolean, etc.

ArrayList Class Diagram

The below class diagram shows Java ArrayList class extends AbstractList class which implements List interface. The List interface extends Collection and Iterable interfaces in hierarchical order.

ArrayList Class Methods

The below class diagram shows the list of methods that the ArrayList class provides. In the next section, I have demonstrated all the methods of ArrayList class with examples.

ArrayList Class Examples

Example 1: Creating an ArrayList and Adding New Elements to It

The below example demonstrates how to create an ArrayList using the ArrayList() constructor and add new elements to an ArrayList using the add() method.
package com.javaguides.collections.arraylistexamples;

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

// How to create an ArrayList using the ArrayList() constructor.
// Add new elements to an ArrayList using the add() method.
public class CreateArrayListExample {

    public static void main(String[] args) {
        // Creating an ArrayList of String using
     List<String> fruits = new ArrayList<>();
        // Adding new elements to the ArrayList
     fruits.add("Banana");
     fruits.add("Apple");
     fruits.add("mango");
     fruits.add("orange");
        System.out.println(fruits);
    }
}
Output:
[Banana, Apple, mango, orange]

Example 2: Example Demonstrates How the ArrayList Contains Duplicate and Null Values

package com.javaguides.collections.arraylistexamples;

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

public class NullAndDuplicateValuesDemo {

    public static void main(String[] args) {
        nullValueDemo();
        duplicateValueDemo();
    }

    private static void nullValueDemo() {

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

         list.add(null);

         list.add(null);
 
         System.out.println(list.toString());
    }

    private static void duplicateValueDemo() {

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

         list.add("duplicate");
  
         list.add("duplicate");
 
          System.out.println(list.toString());

    }
}
Output:
[null, null]
[duplicate, duplicate]

Example 3: Creating an ArrayList From Another Collection

package com.javaguides.collections.arraylistexamples;

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

// How to create an ArrayList from another collection using the 
// ArrayList(Collection c) constructor.

// How to add all the elements from an existing collection to the new 
// ArrayList using the addAll() method.

public class CreateArrayListFromCollectionExample {

    public static void main(String[] args) {
     
     // Create an arraylist
        List<Integer> firstFivePrimeNumbers = new ArrayList<>();
        firstFivePrimeNumbers.add(2);
        firstFivePrimeNumbers.add(3);
        firstFivePrimeNumbers.add(5);
        firstFivePrimeNumbers.add(7);
        firstFivePrimeNumbers.add(11);

        // Creating an ArrayList from another collection
        List<Integer> firstTenPrimeNumbers = new ArrayList<>(firstFivePrimeNumbers);


        List<Integer> nextFivePrimeNumbers = new ArrayList<>();
        nextFivePrimeNumbers.add(13);
        nextFivePrimeNumbers.add(17);
        nextFivePrimeNumbers.add(19);
        nextFivePrimeNumbers.add(23);
        nextFivePrimeNumbers.add(29);

        // Adding an entire collection to an ArrayList
        firstTenPrimeNumbers.addAll(nextFivePrimeNumbers);

        System.out.println(firstTenPrimeNumbers);
    }
}
Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Example 4: Accessing Elements from an ArrayList

package com.javaguides.collections.arraylistexamples;

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

// How to check if an ArrayList is empty using the isEmpty() method.
// How to find the size of an ArrayList using the size() method.
// How to access the element at a particular index in an ArrayList using the get() method.
// How to modify the element at a particular index in an ArrayList using the set() method.

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

        // Check if an ArrayList is empty
        System.out.println("Is the topProgrammingLanguages list empty? : " 
                            + topProgrammingLanguages.isEmpty());

        topProgrammingLanguages.add("C");
        topProgrammingLanguages.add("Java");
        topProgrammingLanguages.add("C++");
        topProgrammingLanguages.add("Python");
        topProgrammingLanguages.add(".net");

        // Find the size of an ArrayList
        System.out.println("Here are the top " + topProgrammingLanguages.size() 
                          + " Programming Languages in the world");
        System.out.println(topProgrammingLanguages);

        // Retrieve the element at a given index
        String bestProgrammingLang = topProgrammingLanguages.get(1);
        String secondBestProgrammingLang = topProgrammingLanguages.get(1);
        String dotNetProgrammingLang = topProgrammingLanguages
          .get(topProgrammingLanguages.size() - 1);

        System.out.println("best Programming Lang: " + bestProgrammingLang);
        System.out.println("Second Best Programming Lang: " + secondBestProgrammingLang);
        System.out.println("Dot Net Programming Lang: " + dotNetProgrammingLang);

        // Modify the element at a given index
        topProgrammingLanguages.set(4, "C#");
        System.out.println("Modified top Programming Languages list: " + topProgrammingLanguages);
    }
}
Output:
Is the topProgrammingLanguages list empty? : true
Here are the top 5 Programming Languages in the world
[C, Java, C++, Python, .net]
best Programming Lang: Java
Second Best Programming Lang: Java
Dot Net Programming Lang: .net
Modified top Programming Languages list: [C, Java, C++, Python, C#]

Example 5: Removing Elements from an ArrayList

package net.javaguides.springboot;

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

/**
 * Program to Removing elements from an ArrayList
 * @author RAMESH
 *
 */
public class RemoveElementsArrayList {
    public static void main(String[] args) {
        // Creating an ArrayList of String using
        List < String > fruits = new ArrayList < > ();
        // Adding new elements to the ArrayList
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Orange");
        fruits.add("Pineapple");
        fruits.add("Grapes");

        System.out.println(fruits);

        // Remove the element at index `5`
        fruits.remove(5);
        System.out.println("After remove(5): " + fruits);

        // Remove the first occurrence of the given element from the ArrayList
        // (The remove() method returns false if the element does not exist in the
        // ArrayList)
        boolean isRemoved = fruits.remove("Mango");
        System.out.println("After remove(\"Mango\"): " + fruits);

        // Remove all the elements that exist in a given collection
        List < String > subfruitsList = new ArrayList < > ();
        subfruitsList.add("Apple");
        subfruitsList.add("Banana");

        fruits.removeAll(subfruitsList);
        System.out.println("After removeAll(subfruitsList): " + fruits);

        // Remove all elements from the ArrayList
        fruits.clear();
        System.out.println("After clear(): " + fruits);
    }
}
Output:
[Banana, Apple, Mango, Orange, Pineapple, Grapes]
After remove(5): [Banana, Apple, Mango, Orange, Pineapple]
After remove("Mango"): [Banana, Apple, Orange, Pineapple]
After removeAll(subfruitsList): [Orange, Pineapple]
After clear(): []

Example 6: Iterating over an ArrayList

package com.javaguides.collections.arraylistexamples;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

// Java 8 forEach and lambda expression.
// iterator().
// iterator() and Java 8 forEachRemaining() method.
// listIterator().
// Simple for-each loop.
// for loop with index.

public class IterateOverArrayListExample {
    public static void main(String[] args) {
     // Creating an ArrayList of String using
     List<String> fruits = new ArrayList<>();
        // Adding new elements to the ArrayList
     fruits.add("Banana");
     fruits.add("Apple");
     fruits.add("mango");
     fruits.add("orange");
     fruits.add("Watermelon");
     fruits.add("Strawberry");

        System.out.println("=== Iterate using Java 8 forEach and lambda ===");
        fruits.forEach(fruit -> {
            System.out.println(fruit);
        });

        System.out.println("\n=== Iterate using an iterator() ===");
        Iterator<String> fruitsIterator = fruits.iterator();
        while (fruitsIterator.hasNext()) {
            String tvShow = fruitsIterator.next();
            System.out.println(tvShow);
        }

        System.out.println("\n=== Iterate using an iterator() and Java 8 forEachRemaining() method ===");
        fruitsIterator = fruits.iterator();
        fruitsIterator.forEachRemaining(fruit -> {
            System.out.println(fruit);
        });

        System.out.println("\n=== Iterate using a listIterator() to traverse in both directions ===");
        // Here, we start from the end of the list and traverse backwards.
        ListIterator<String> listIterator = fruits.listIterator(fruits.size());
        while (listIterator.hasPrevious()) {
            String fruit = listIterator.previous();
            System.out.println(fruit);
        }

        System.out.println("\n=== Iterate using simple for-each loop ===");
        for(String fruit: fruits) {
            System.out.println(fruit);
        }

        System.out.println("\n=== Iterate using for loop with index ===");
        for(int i = 0; i < fruits.size(); i++) {
            System.out.println(fruits.get(i));
        }
    }
}
Output:
=== Iterate using Java 8 forEach and lambda ===
Banana
Apple
mango
orange
Watermelon
Strawberry

=== Iterate using an iterator() ===
Banana
Apple
mango
orange
Watermelon
Strawberry

=== Iterate using an iterator() and Java 8 forEachRemaining() method ===
Banana
Apple
mango
orange
Watermelon
Strawberry

=== Iterate using a listIterator() to traverse in both directions ===
Strawberry
Watermelon
orange
mango
Apple
Banana

=== Iterate using simple for-each loop ===
Banana
Apple
mango
orange
Watermelon
Strawberry

=== Iterate using for loop with index ===
Banana
Apple
mango
orange
Watermelon
Strawberry

Example 7: Searching for Elements in an ArrayList

package com.javaguides.collections.arraylistexamples;

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

// Check if an ArrayList contains a given element | contains()

// Find the index of the first occurrence of an element in an ArrayList | indexOf()

// Find the index of the last occurrence of an element in an ArrayList | lastIndexOf()

public class SearchElementsInArrayListExample {
    public static void main(String[] args) {
      // Creating an ArrayList of String using
     List<String> fruits = new ArrayList<>();
        // Adding new elements to the ArrayList
     fruits.add("Banana");
     fruits.add("Apple");
     fruits.add("mango");
     fruits.add("orange");
     fruits.add("Watermelon");
     fruits.add("Strawberry");
     
        // Check if an ArrayList contains a given element
        System.out.println("Does names array contain \"mango\"? : " + fruits.contains("mango"));

        // Find the index of the first occurrence of an element in an ArrayList
        System.out.println("indexOf \"Banana\": " + fruits.indexOf("Banana"));
        System.out.println("indexOf \"Apple\": " + fruits.indexOf("Apple"));

        // Find the index of the last occurrence of an element in an ArrayList
        System.out.println("lastIndexOf \"Watermelon\" : " + fruits.lastIndexOf("Watermelon"));
        System.out.println("lastIndexOf \"Strawberry\" : " + fruits.lastIndexOf("Strawberry"));
    }
}
Output:
Does names array contain "mango"? : true
indexOf "Banana": 0
indexOf "Apple": 1
lastIndexOf "Watermelon" : 4
lastIndexOf "Strawberry" : 5

Example 8: ArrayList of User-Defined Objects

package com.javaguides.collections.arraylistexamples;

public class Student {
 
    private String name;
    private String college;
 
   public Student(String name, String college) {
      super();
      this.name = name;
      this.college = college;
   }
 
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getCollege() {
      return college;
   }
   public void setCollege(String college) {
      this.college = college;
   }
}
package com.javaguides.collections.arraylistexamples;

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

public class ArrayListUserDefinedObjectExample {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Ramesh", "ABC"));
        students.add(new Student("Prakash", "ABC"));
        students.add(new Student("Tony", "ABC"));

        students.forEach(user -> {
            System.out.println("Name : " + user.getName() + ", College : " + user.getCollege());
        });
    }
}
Output:
Name : Ramesh, College : ABC
Name : Prakash, College : ABC
Name : Tony, College : ABC

Example 9: Sorting an ArrayList

package com.javaguides.collections.arraylistexamples;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

// Sort an ArrayList using Collections.sort() method.
// Sort an ArrayList using ArrayList.sort() method.
// Sort an ArrayList of user defined objects with a custom comparator.

public class ArrayListSortExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Tony");
        names.add("Tom");
        names.add("Johnson");
        names.add("John");
        names.add("Ramesh");
        names.add("Sanjay");
        
        System.out.println("Names : " + names);

        // Sort an ArrayList using its sort() method. You must pass a Comparator to the ArrayList.sort() method.
        names.sort(new Comparator<String>() {
            @Override
            public int compare(String name1, String name2) {
                return name1.compareTo(name2);
            }
        });

        // The above `sort()` method call can also be written simply using lambda expression
        names.sort((name1, name2) -> name1.compareTo(name2));

        // Following is an even more concise solution
        names.sort(Comparator.naturalOrder());

        System.out.println("Sorted Names : " + names);
    }
}
Output:
Names : [Tony, Tom, Johnson, John, Ramesh, Sanjay]
Sorted Names : [John, Johnson, Ramesh, Sanjay, Tom, Tony]

Example 10: Java List.of() API

Since Java 9, we have a couple of factory methods for creating lists having a handful of elements. The created list is immutable.
import java.util.List;

public class ListOf {

    public static void main(String[] args) {

        var words = List.of("wood", "forest", "falcon", "eagle");
        System.out.println(words);

        var values = List.of(1, 2, 3);
        System.out.println(values);
    }
}

What's Next?

In this tutorial, we have learned all about the ArrayList class of the Collections framework with an example.

References

Related Collections Examples

Comments