Java ArrayList.contains() Method

 Posted On  | Yashwant Chavan 

In this tutorial you will learn how to check if element is exist or not in the ArrayList. java.util.ArrayList.contains() method returns true if this list contains the specified element otherwise it return false value.

syntax

Returns true if this list contains the specified element.

boolean java.util.ArrayList.contains(Object o)

Parameter

o element whose presence in this list is to be tested.

Return

true if this list contains the specified element

Java ArrayList.contains() example

Refer below steps

  • Constructs an empty ArrayList with an initial capacity using new ArrayList<String>().
  • Add some elements in colors ArrayList using add() method.
  • Check if element contains or not in the ArrayList ( colors.contains("Pink") ). It return true if element exist in the List otherwise return false.
package com.technicalkeeda.app;

import java.util.ArrayList;

public class ArrayListContains {
    public static void main(String[] args) {

        ArrayList <String> colors = new ArrayList <String> ();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");
        colors.add("White");
        colors.add("Pink");

        System.out.println("colors List contains Pink ? " + colors.contains("Pink"));
        System.out.println("colors List contains Yellow ? " + colors.contains("Yellow"));

    }
}

Output

colors List contains Pink ? true
colors List contains Yellow ? false


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0217 seconds.