Java Collection How to - Compare for Equality








Question

We would like to know how to compare for Equality.

Answer

The ArrayList class gets its equals() method from the AbstractList class:

public boolean equals(Object o)

An ArrayList is equal to another object if the other object implements the List interface, has the same size(), and contains the same elements in the same positions.

import java.util.Arrays;
import java.util.List;
public class MainClass {
//from  w w w . j a v a 2 s . com
  public static void main(String[] a) {

    List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
    List list2 = Arrays.asList(new String[] { "A", "B", "C" });

    System.out.println(list.equals(list2));
  }
}

The code above generates the following result.