SoFunction
Updated on 2025-04-27

Summary of the use of contains method in Java util package

In Java programming, collections are important tools for storing and manipulating a set of objects. Java's package provides a variety of collection classes, such as ArrayList, HashSet, LinkedList, etc. These classes greatly simplify the complexity of data management. The contains() method is one of the most commonly used methods among these collection classes, and is used to determine whether a collection contains a specific element. This article will introduce in detail the usage, application scenarios and precautions of the contains() method.

1. What is the contains() method?

The contains() method is a method in the Collection interface that checks whether the specified element exists in the collection. This method is implemented in multiple collection classes, such as ArrayList, HashSet, LinkedList, etc.

Method signature

public boolean contains(Object o)

Parameters and return values

Parameters: The contains() method accepts an Object type parameter, that is, to check whether elements that exist in the collection are present.
Return value: Return true if the collection contains the specified element; otherwise return false.

2. Example of using contains() method

Example 1: Use contains() in ArrayList

ArrayList is one of the most commonly used collection classes in Java. We can use the contains() method to check whether ArrayList contains an element.

import ;

public class ContainsExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        
        // Add elements to ArrayList        ("Java");
        ("Python");
        ("C++");
        
        // Check whether ArrayList contains "Python"        boolean containsPython = ("Python");
        ("Does ArrayList contain 'Python': " + containsPython);  // Output: true        
        // Check whether ArrayList contains "Ruby"        boolean containsRuby = ("Ruby");
        ("Does ArrayList contain 'Ruby': " + containsRuby);  // Output: false    }
}

In this example, the contains() method is used to check whether the ArrayList contains "Python" and "Ruby". The results show that ArrayList contains "Python" but not "Ruby".

Example 2: Use contains() in HashSet

HashSet is a collection class that does not allow duplicate elements. Use the contains() method to easily check whether an element exists in the HashSet.

import ;

public class ContainsExample {
    public static void main(String[] args) {
        HashSet<Integer> set = new HashSet<>();
        
        // Add elements to HashSet        (10);
        (20);
        (30);
        
        // Check whether HashSet contains 20        boolean containsTwenty = (20);
        ("Does HashSet contain '20': " + containsTwenty);  // Output: true        
        // Check whether HashSet contains 40        boolean containsForty = (40);
        ("Does HashSet contain '40': " + containsForty);  // Output: false    }
}

In this example, the contains() method is used to check if the HashSet contains 20 and 40. The results show that HashSet contains 20, but not 40.

3. Application scenarios of the contains() method

3.1 User permission verification

When implementing a user permission system, we can use the contains() method to check whether the user has a specific permission.

import ;

public class PermissionExample {
    public static void main(String[] args) {
        HashSet<String> userPermissions = new HashSet<>();
        ("READ");
        ("WRITE");
        
        // Check whether the user has "EXECUTE" permission        boolean hasExecutePermission = ("EXECUTE");
        ("Does the user have 'EXECUTE' permission: " + hasExecutePermission);  // Output: false    }
}

3.2 Prevent repeated addition of elements

In some application scenarios, we may need to prevent duplicate elements in the collection. You can use the contains() method to check whether an element already exists and decide whether to add it.

import ;

public class UniqueElementExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        String element = "Java";
        
        // Add only if the collection does not contain the element        if (!(element)) {
            (element);
        }
        
        ("ArrayList: " + list);
    }
}

3.3 String processing

When working with strings or text, we can use the contains() method to check whether a specific keyword exists in a list or collection.

import ;

public class KeywordSearchExample {
    public static void main(String[] args) {
        ArrayList<String> keywords = new ArrayList<>();
        ("Java");
        ("Programming");
        ("Tutorial");
        
        String searchKeyword = "Java";
        
        // Check whether the keyword exists        if ((searchKeyword)) {
            ("Keyword '" + searchKeyword + "' exists in the list");
        } else {
            ("Keyword '" + searchKeyword + "' does not exist in the list");
        }
    }
}

4. Things to note about the contains() method

There are several key points to note when using the contains() method:

Element comparison: The contains() method uses the equals() method to compare whether the elements are the same. Therefore, it is important to ensure that the objects stored in the collection correctly implement the equals() method.

Performance considerations: The performance performance of the contains() method is different in different collection classes. For ArrayList, the time complexity of contains() is O(n), because it needs to be compared one element by element; for HashSet, the time complexity of contains() is usually O(1), because it looks up based on a hash table.

Thread safety: If multiple threads access the same collection concurrently and call contains(), it is necessary to ensure the thread safety of the collection. You can use thread-safe collection classes such as ConcurrentHashMap.

5. Summary

The contains() method in the Java util package is an important tool in collection operations, which provides a simple and efficient way to check whether specific elements exist in a collection. Whether it is in permission verification, preventing duplicate addition of elements, or in situations such as text processing, the contains() method can play an important role. By understanding how the contains() method is used and its considerations, developers can better operate and manage collection data.

This is the article about the summary of the contains() method in the Java util package. For more related contents of the contains() method in the Java util package, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!