VOOZH about

URL: https://www.geeksforgeeks.org/java/comparing-two-arraylist-in-java/

⇱ Comparing two ArrayList In Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Comparing two ArrayList In Java

Last Updated : 23 Jan, 2026

In Java, an ArrayList is used to store an ordered collection of elements. To compare two ArrayList objects, Java provides the equals() method. This method checks whether both lists have the same size and contain the same elements in the same order, making it a simple and reliable way to compare lists.

Example:


Output
true

Explanation:

  • Creates two ArrayLists list1 and list2 with the same elements [1, 2, 3].
  • Uses list1.equals(list2) to check if both lists are equal.
  • Prints true because both lists have the same size and elements in the same order.

Syntax

boolean equals(Object o)

  • Parameter: "o" the object to be compared
  • Return Type: Returns true if both ArrayList objects are equal; otherwise, returns false

Example: This program demonstrates how to compare two ArrayList objects in Java using the equals() method.


Output
ArrayList1 = [item 1, item 2, item 3, item 4]
ArrayList2 = [item 1, item 2, item 3, item 4]
Array Lists are equal
Adding one more element to ArrayList1
ArrayList1 = [item 1, item 2, item 3, item 4, it...

Explanation:

  • Two ArrayList objects list1 and list2 are created.
  • list1.equals(list2) checks if both lists are equal (same size and elements in the same order).
Comment