What is ArrayList?
The ArrayList class is a resizable array, which can be found in the java.util package. ArrayList objects are created in the same fashion as other object classes. The primary difference with ArrayLists is that the element type of the ArrayList must be specified using arrows (<>).
Java ArrayList contains()
The contains() method checks if the specified element is present in the arraylist.
contains() Return Value
- returns true if the specified element is present in the arraylist.
- returns false if the specified element is not present in the arraylist.
Let us create 2 ArrayLists.
import java.util.ArrayList;
import java.util.Arrays;
public class Compare_ArrayList {
public static void main(String[] args) {
ArrayList<String> list1 = new ArrayList<String>();
list1.add("Java");
list1.add("Python");
list1.add("PHP");
list1.add("JavaScript");
list1.add("Ruby");
ArrayList<String> list2 = new ArrayList<>(Arrays.asList("Python", "Ruby"));
System.out.println("ArrayList1:" + list1);
System.out.println("ArrayList2:" + list2);
System.out.println("Check PHP is present in arrayList1 :" + list1.contains("PHP"));
System.out.println("Check Cobol is present in arrayList1 :" + list1.contains("Cobol"));
System.out.println("Compare 2 arrayList using contains: " + list1.contains(list2));
}
}
The output of the above program is
When we are comparing 2 ArrayList, then both the ArrayList should contain the same elements in the same sequence.
In the below example, the sequence of the elements is different, so the method returns false.
import java.util.ArrayList;
import java.util.Arrays;
public class Compare_ArrayList {
public static void main(String[] args) {
ArrayList<String> list1 = new ArrayList<String>();
list1.add("Java");
list1.add("Python");
list1.add("PHP");
list1.add("JavaScript");
list1.add("Ruby");
ArrayList<String> list3 = new ArrayList<>(Arrays.asList("Python", "Java", "Ruby", "PHP", "JavaScript"));
System.out.println("ArrayList1:" + list1);
System.out.println("ArrayList2:" + list2);
System.out.println("Compare 2 arrayList using contains with different sequence: " + list1.contains(list3));
}
}
The output of the above program is
That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!