Languages
[Edit]
EN

Java - compare two ArrayLists

0 points
Created by:
Broncono
466

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java Collections - ArrayList

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join