DEV Community

loading...
Cover image for How to compare two Arraylist in java?

How to compare two Arraylist in java?

joshuabrown0010 profile image joshua-brown0010 ・1 min read

In this article, we will learn what is an ArrayList and different methods of comparing an ArrayList in java. An example program will be described below for the audience to understand.

ArrayList in JAVA

Unlike the normal array, ArrayList is a resizable array where one can add, remove, access, or change an element in an array at any time. This is not possible with a normal array and the syntax for this ArrayList is shown below as follows.

Syntax

ArrayList< DataType> arrayListname = new ArrayList< DataType>();

Approach

  • I have stated an example regarding the usage of equals() method in java to compare two ArrayLists.
  • As far as syntax is concerned, boolean equals(Object o). It returns true if the object matches with the list or else return false
  • I have declared two strings ArrayLists named list1 and list2, and by using java,util.ArrayList package, I have added list items to list1 and list2.
  • In the next step, I have compared two lists by using the equals() method, such that it returns true, as both the items in the lists are ideal.
  • In the last step, I have added another item to the list1, but not list2 and compared once again and the final output is resulted as false because the number of items is more and not equal. This is how we compare two ArrayLists and I have used the equals( ) method as an example.
  • There are other methods like the removeAll(), retainAll(), contains() methods can also be used for comparison. Read more

Discussion (0)

pic
Editor guide