Check two ArrayList for equality in Java


Two ArrayList can be compared to check if they are equal or not using the method java.util.ArrayList.equals(). This method has a single parameter i.e. an ArrayList that is compared with the current object. It returns true if the two ArrayList are equal and false otherwise.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List aList1 = new ArrayList();
      aList1.add("Sun");
      aList1.add("Moon");
      aList1.add("Stars");
      List aList2 = new ArrayList();
      aList2.add("Sun");
      aList2.add("Moon");
      aList2.add("Stars");
      System.out.println("The two ArrayList are equal? " + aList1.equals(aList2));
   }
}

Output

The two ArrayList are equal? true

Now let us understand the above program.

The ArrayList aList1 and aList2 are created and ArrayList.add() is used to add the elements to the two ArrayList. Then ArrayList.equals() method is used to check if the ArrayList are equal or not and the result is displayed. A code snippet which demonstrates this is as follows −

List aList1 = new ArrayList();
aList1.add("Sun");
aList1.add("Moon");
aList1.add("Stars");
List aList2 = new ArrayList();
aList2.add("Sun");
aList2.add("Moon");
aList2.add("Stars");
System.out.println("The two ArrayList are equal? " + aList1.equals(aList2));

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

655 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements