Check if two ArrayList are equal in java | Java @ Desk
Home » , » Check if two ArrayList are equal in java

Check if two ArrayList are equal in java

Check if two ArrayList are equal in java

ArrayList is considered equals when :
1) Size of both the lists is same
2) Content of both the list is same
3) Ordering of element is same

There are two ways to check if the lists are equals
1) Using equals() method - When using this method, make sure the ordering of elements is also same. Then only this will return true
2) Using containsAll() method - This does not check for ordering of elements. It only checks if all the elements are present in other list. It returns true even if ordering of element is different.

In containsAll, the check would be listOne.containsAll(listTwo) && listTwo.containsAll(listOne)

Client File

package test;

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

public class ArrayListEquals {

 public static void main(String args[]) {
  List<Integer> integerOne = new ArrayList<Integer>();
  List<Integer> integerTwo = new ArrayList<Integer>();

  integerOne.add(10);
  integerOne.add(20);

  integerTwo.add(10);
  integerTwo.add(20);

  boolean equals = integerOne.equals(integerTwo);
  boolean containsAll = integerOne.containsAll(integerTwo)
    && integerTwo.containsAll(integerOne);

  System.out.println(equals);
  System.out.println(containsAll);
 }
}




0 comments:

Post a Comment