EN
Java - compare two ArrayLists
0
points
In this article, we would like to show you how to compare two ArrayLists in Java.
Quick solution:
firstList.equals(secondList));
Practical examples
Example 1
In this example, we create two identical ArrayLists and use equals()
method to compare them.
import java.util.*;
public class Example {
public static void main(String[] args) {
List<String> firstList = new ArrayList<>();
List<String> secondList = new ArrayList<>();
// add items to the ArrayLists
firstList.add("1");
firstList.add("2");
firstList.add("3");
secondList.add("1");
secondList.add("2");
secondList.add("3");
// reverse ArrayList
System.out.println(firstList.equals(secondList));
}
}
Output:
true
Example 2
In this example, we create two different ArrayLists and use equals()
method to compare them.
import java.util.*;
public class Example {
public static void main(String[] args) {
List<String> firstList = new ArrayList<>();
List<String> secondList = new ArrayList<>();
// add items to the ArrayLists
firstList.add("1");
firstList.add("2");
firstList.add("3");
secondList.add("4");
secondList.add("5");
secondList.add("6");
// reverse ArrayList
System.out.println(firstList.equals(secondList));
}
}
Output:
false