Two lists are equal if they consist of same number of elements in the same order.
Let’s say we have the following two lists −
List<Integer>arrList1 = Arrays.asList(new Integer[] { 10, 20, 30, 45, 55, 70, 90, 100 }); List<Integer>arrList2 = Arrays.asList(new Integer[] {15, 25, 35, 50, 55, 75, 95, 120});
Now, let’s find out whether both the lists are equal or not −
arrList1.equals(arrList2);
If both the above lists have equal elements, then TRUE is returned, else FALSE is the return value.
import java.util.Arrays; import java.util.List; public class Demo { public static void main(String[] a) { List<Integer>arrList1 = Arrays.asList(new Integer[] { 10, 20, 30, 45, 55, 70, 90, 100 }); List<Integer>arrList2 = Arrays.asList(new Integer[] {15, 25, 35, 50, 55, 75, 95, 120}); List<Integer>arrList3 = Arrays.asList(new Integer[] { 10, 20, 30, 45, 55, 70, 90, 100}); System.out.println("Are List 1 and List2 equal? "+arrList1.equals(arrList2)); System.out.println("Are List 2 and List3 equal? "+arrList2.equals(arrList2)); System.out.println("Are List 1 and List3 equal? "+arrList1.equals(arrList3)); } }
Are List 1 and List2 equal? false Are List 2 and List3 equal? true Are List 1 and List3 equal? true