Java ArrayList Example

In this tutorial, we’re going to take a look at the important ArrayList class methods with examples.
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface.
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.

ArrayList Class Methods

The below class diagram shows the ArrayList class methods:

Let's understand important ArrayList class methods with examples.

ArrayList add() method

ArrayList add() method is used to add an element in the list.
Example: The following example shows the usage of java.util.ArrayList.add(E) 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]

Java ArrayList addAll() Method

The ArrayList addAll() method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.

Example:  
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]

Java ArrayList get() Method

The java.util.ArrayList.get(int index) method returns the element at the specified position in this list.

Example: 
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#]

Java ArrayList remove(), removeAll() and clear() Methods

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(): []

ArrayList isEmpty(), size(), set(), and get() Methods

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#]

ArrayList indexOf() and lastIndexOf() methods

indexOf() and lastIndexOf() methods can use to search an element in the list with specific index.
Please refer comments in source code are self descriptive.
private static void searchListDemo() {
    List<String> searchList = new ArrayList();
    searchList.add("element 1");
    searchList.add("element 2");
    searchList.add("element 3");
    searchList.add("element 4");

    // Returns the index of the first occurrence of the specified element in
    // this list,
    // or -1 if this list does not contain the element.
    int index = searchList.indexOf("element 2");
    System.out.println(" search element at index 0 --->" + index);

    // Returns the index of the last occurrence of the specified element in
    // this list,
    // or -1 if this list does not contain the element
    int lastIndex = searchList.lastIndexOf("element 2");
    System.out.println(" search element at lastIndex 0 --->" + lastIndex);
}

ArrayList subList() Method

The range-view operation, subList(int fromIndex, int toIndex), returns a List view of the portion of this list whose indices range from fromIndex, inclusive, to toIndex, exclusive.
//Returns a view of the portion of this list between the specified fromIndex, 
//inclusive, and toIndex, exclusive. 
public void rangeViewDemo(){
    List<String> list = new LinkedList<>();
    list.add("element 1");
    list.add("element 2");
    list.add("element 3");
    list.add("element 4");
   
    //If fromIndex and toIndex are equal, the returned list is empty.) 
    for(String str : list.subList(0, 0)){
        System.out.println(" sub list demo --" + str);
    }
   
    for(String str : list.subList(0, 1)){
        System.out.println(" sub list demo --" + str);
    }
}

ArrayList addAll(), retainAll(), removeAll() and containsAll() Methods

Perform bulk operations using ArrayList:
private static void bulkOperationDemo() {
    List<String> list = new ArrayList<>();
    list.add("element 1");
    list.add("element 2");
    list.add("element 3");
    list.add("element 4");

     // addAll() - Appends all of the elements in the specified collection to
     // the end of this list,
     // in the order that they are returned by the specified collection's
     // iterator (optional operation).
    List<String> union = new ArrayList<>();
    union.addAll(list);
    printMessage(union, "addALL operation example ");

    // Retains only the elements in this list that are contained in
    // the specified collection (optional operation).
    List<String> intersection = new ArrayList<>();
    intersection.add("element 1");
    intersection.add("element 2");
    intersection.add("element 3");
    intersection.add("element 4");
    System.out.println("retainAll -- > " + intersection.retainAll(list));

    // Removes from this list all of its elements that are
    // contained in the specified collection (optional operation).
    List<String> difference = new ArrayList<>();
    difference.add("element 1");
    difference.add("element 2");
    difference.add("element 3");
    difference.add("element 4");
    System.out.println("removeAll operation example ---> " + difference.removeAll(list));
    printMessage(difference, "removeAll operation example ");  

    List<String> checking = new ArrayList<>();
    checking.add("element 1");
    checking.add("element 2");
    checking.add("element 3");
    checking.add("element 4");
    System.out.println("containsAll operation example ---- > " + checking.containsAll(list));
}

private static void printMessage(List<String> list, String message) {
 list.forEach(key -> System.out.println(message + key));
}
Output :
addALL operation example element 1

addALL operation example element 2

addALL operation example element 3

addALL operation example element 4

retainAll -- > false

removeAll operation example ---> true

containsAll operation example ---- > true

ArrayList forEach() Method

Iterating over an ArrayList:
// Three ways to iterator list
private static void iterateDemo() {
    List<String> list = new LinkedList<>();
    list.add("element 1");
    list.add("element 2");
    list.add("element 3");
    list.add("element 4");

    // using Iterator
    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
         String str = iterator.next();
         System.out.println(" only forward direction ---" + str);
    }
  
    // Using advanced for loop
    for (String str : list) {
          System.out.println(" only forward direction ---" + str);
    }
 
     // Java 8
    list.forEach(str -> System.out.println(" only forward direction ---" + str));
}

Related Collections Examples

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments