How to compare two ArrayList for equality in Java?


You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.

Example

 Live Demo

import java.util.ArrayList;

public class ComparingList {
   public static void main(String[] args) {
      ArrayList<String> list1 = new ArrayList<String>();
      list1.add("JavaFx");
      list1.add("Java");
      list1.add("WebGL");
      list1.add("OpenCV");
      ArrayList<String> list2 = new ArrayList<String>();
      list2.add("JavaFx");
      list2.add("Java");
      list2.add("WebGL");
      list2.add("OpenCV");
      System.out.println(list2);
      System.out.println(list1.equals(list2));
   }
}

Updated on: 30-Jul-2019

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements