Java ArrayList contains() Method

Java ArrayList Java ArrayList

The contains() method is used to determine whether an element exists in the dynamic array.

The syntax of the contains() method is:

arraylist.contains(Object obj)

Note:arraylist is an object of the ArrayList class.

Parameter Description:

  • obj - The element to be detected

Return Value

Returns true if the specified element exists in the dynamic array.

Returns false if the specified element does not exist in the dynamic array.

Example

A String-type dynamic array using the contains() method:

Example

import java.util.ArrayList;

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

        // Create an array
        ArrayList<String> sites = new ArrayList<>();

        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");
        System.out.println("Website list: " + sites);


        // Check if Example is in this array
        System.out.print("Does Example exist in arraylist: ");
        System.out.println(sites.contains("Example"));

        // Check if Weibo is in this array
        System.out.print("Does Weibo exist in arraylist: ");
        System.out.println(sites.contains("Weibo"));
    }
}

Executing the above program outputs the result:

Example 是否存在于 arraylist: true
Weibo 是否存在于 arraylist: false

In the above example, we create a dynamic array named sites. Note the expression:

sites.contains("Example")
sites.contains("Weibo")

In the above code, the contains() method checks whether Example exists in the dynamic array. Since Example exists, the method returns true. However, Weibo does not exist in the list, so the method returns false.

Note:The contains() method actually uses the equals() method internally to find elements. If the specified element matches an element in the array, the method returns true.

An Integer-type dynamic array using the contains() method:

Example

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // Create an array
        ArrayList<Integer> numbers = new ArrayList<>();

        // Insert elements into the array
        numbers.add(2);
        numbers.add(3);
        numbers.add(5);
        System.out.println("Number ArrayList: " + numbers);

        // Check if 3 is in this array
        System.out.print("Is 3 in arraylist: ");
        System.out.println(numbers.contains(3));

        // Check if 1 is in this array
        System.out.print("Is 1 in arraylist: ");
        System.out.println(numbers.contains(1));
    }
}

Executing the above program outputs the result:

Number ArrayList: [2, 3, 5]
3 是否在 arraylist: true
1 是否在 arraylist: false

In the above code, the contains() method checks whether 3 exists in the dynamic array. Since 3 exists, the method returns true. However, 1 does not exist in the list, so the method returns false.

Java ArrayList Java ArrayList

Other Extensions