Contains list java contains() in Java ArrayList

In Java, the term “contains list java” is used to check whether a particular object or element is present in a list or collection.

The ArrayList method contains() is used to check specified elements in List.

Contains Syntax

public boolean contains​(Object o)

  1. Parameters: The method takes a single parameter, which is the object or element that you want to check for in the list.
  2. Return Value: The method returns a boolean value, which is “true” if the list contains the specified element, and “false” otherwise.

The contains method is then used to check if the list contains a specific element. In this case, the code checks if the numbers list contains the element 30 by passing it as an argument to the contains method. The result is stored in the containsElement boolean variable.

Similar way we again check for value 100.

Finding a name in String Array List

Here an ArrayList is created and we find the value “Apple” using contains method.

Checking Student name in ArrayList

The code creates an ArrayList called studentList and adds four student names to it. It then checks if the name “Nita” is present in the list using the contains method. Based on the result, it prints whether “Nita” is present or not.

Checking an object in List of Objects

In the Student class, there are private instance variables id, rollNo, name, mailId, and mobileNo representing the attributes of a student. The class also provides a constructor to initialize these attributes, as well as a getter method for the name attribute.

The toString method is overridden to provide a string representation of a Student object, displaying all the attributes.

In the main method, an ArrayList named studentList is created to store Student objects. Four Student objects are created using the constructor and added to the studentList.

A search student object is created by referencing the first student object. The contains method is then used to check if the searchStudent is present in the studentList. The result is stored in the isStudentPresent variable.

Read More

how to return array, arraylist, object from a method in java