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:
xxxxxxxxxx
1
firstList.equals(secondList));
In this example, we create two identical ArrayLists and use equals()
method to compare them.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
List<String> firstList = new ArrayList<>();
7
List<String> secondList = new ArrayList<>();
8
9
// add items to the ArrayLists
10
firstList.add("1");
11
firstList.add("2");
12
firstList.add("3");
13
14
secondList.add("1");
15
secondList.add("2");
16
secondList.add("3");
17
18
// reverse ArrayList
19
System.out.println(firstList.equals(secondList));
20
}
21
}
Output:
xxxxxxxxxx
1
true
In this example, we create two different ArrayLists and use equals()
method to compare them.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
List<String> firstList = new ArrayList<>();
7
List<String> secondList = new ArrayList<>();
8
9
// add items to the ArrayLists
10
firstList.add("1");
11
firstList.add("2");
12
firstList.add("3");
13
14
secondList.add("4");
15
secondList.add("5");
16
secondList.add("6");
17
18
// reverse ArrayList
19
System.out.println(firstList.equals(secondList));
20
}
21
}
Output:
xxxxxxxxxx
1
false