Comparing two ArrayList In Java

Last Updated : 23 Jan, 2026

In Java, an ArrayList is used to store an ordered collection of elements. To compare two ArrayList objects, Java provides the equals() method. This method checks whether both lists have the same size and contain the same elements in the same order, making it a simple and reliable way to compare lists.

Example:

Java
import java.util.ArrayList;
import java.util.Arrays;
class GFG {
    public static void main (String[] args) {
         ArrayList<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3));
         ArrayList<Integer> list2 = new ArrayList<>(Arrays.asList(1, 2, 3));
         System.out.println(list1.equals(list2)); 
    }
}

Output
true

Explanation:

  • Creates two ArrayLists list1 and list2 with the same elements [1, 2, 3].
  • Uses list1.equals(list2) to check if both lists are equal.
  • Prints true because both lists have the same size and elements in the same order.

Syntax

boolean equals(Object o)

  • Parameter: "o" the object to be compared
  • Return Type: Returns true if both ArrayList objects are equal; otherwise, returns false

Example: This program demonstrates how to compare two ArrayList objects in Java using the equals() method.

Java
import java.util.ArrayList;
public class GFG {
    public static void main(String[] args) {
        ArrayList<String> list1 = new ArrayList<>();
        ArrayList<String> list2 = new ArrayList<>();

        list1.add("item 1");
        list1.add("item 2");
        list1.add("item 3");
        list1.add("item 4");

        list2.add("item 1");
        list2.add("item 2");
        list2.add("item 3");
        list2.add("item 4");

        System.out.println("ArrayList1 = " + list1);
        System.out.println("ArrayList2 = " + list2);

        if (list1.equals(list2)) {
            System.out.println("Array Lists are equal");
        } else {
            System.out.println("Array Lists are not equal");
        }

        System.out.println("Adding one more element to ArrayList1");
        list1.add("item 5");

        System.out.println("ArrayList1 = " + list1);
        System.out.println("ArrayList2 = " + list2);

        if (list1.equals(list2)) {
            System.out.println("Array Lists are equal");
        } else {
            System.out.println("Array Lists are not equal");
        }
    }
}

Output
ArrayList1 = [item 1, item 2, item 3, item 4]
ArrayList2 = [item 1, item 2, item 3, item 4]
Array Lists are equal
Adding one more element to ArrayList1
ArrayList1 = [item 1, item 2, item 3, item 4, it...

Explanation:

  • Two ArrayList objects list1 and list2 are created.
  • list1.equals(list2) checks if both lists are equal (same size and elements in the same order).
Comment