.contains()
Published Feb 22, 2024
Contribute to Docs
The .contains()
method is declared in the List
interface and implemented in the ArrayList
class. It is used to check if the element is present in the specified ArrayList
or not. The function returns a boolean value of true
if the element is present and false
if not.
Syntax
The .contains()
method can be called on an ArrayList
instance and requires a single parameter:
arrayListInstance.contains(obj);
arrayListInstance
: TheArrayList
on which the.contains()
method is called.obj
: The element whose presence in theArrayList
is to be checked.
Example
In the example below, an empty ArrayList
instance fruitList
is created, which can hold String
type elements. Next, a few fruit names are added with the .add()
method. Lastly, the presence of two fruit names is checked in the ArrayList
with the .contains()
method:
import java.util.ArrayList;public class Fruits {public static void main(String[] args) {ArrayList<String> fruitList = new ArrayList<String>();fruitList.add("Mangos");fruitList.add("Bananas");fruitList.add("Watermelons");fruitList.add("Grapes");// Checking if 'Oranges' and 'Bananas' are present in 'fruitList'boolean areOrangesPresent = fruitList.contains("Oranges");boolean areBananasPresent = fruitList.contains("Bananas");System.out.println("Fruit list contains oranges: "+ areOrangesPresent);System.out.println("Fruit list contains bananas: "+ areBananasPresent);}}
The output of the above example will look like this:
Fruit list contains oranges: falseFruit list contains bananas: true
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.