Java ArrayList.contains(): Checking Element Presence & Equality Rules

The ArrayList.contains(Object o) method returns true if the list contains at least one element matching o (evaluated via Objects.equals(o, element)), and false otherwise.

Related Search Operations: Internally, contains(o) simply evaluates indexOf(o) >= 0 in O(n) linear time. If you need the matching element's position, use ArrayList.indexOf() or ArrayList.lastIndexOf(). To remove the first matching element, use ArrayList.remove(Object).

1. Syntax, Method Signature & Internal Delegation 🔝

Declared in java.util.ArrayList<E>:

 // Returns true if this list contains at least one element e such that Objects.equals(o, e)
public boolean contains(Object o)
Element Type / Value Operational Rule
o Object (nullable) The target element to search for; null is permitted and matched via == null.
Return Value boolean true if at least one match is found (indexOf(o) >= 0); false otherwise.
Time Complexity O(n) Scans from index 0 to size - 1, stopping at the first match.

2. Basic String Membership Check 🔝

Testing whether a specific string exists inside an ArrayList<String> using an if-else statement:

import java.util.ArrayList;

ArrayList<String> languages = new ArrayList<String>();
languages.add("Java");
languages.add("PHP");
languages.add("Python");
System.out.println(languages);

if (languages.contains("PHP")) {
    System.out.println("PHP is available");
} else {
    System.out.println("PHP is NOT available");
}

Terminal Output:

[Java, PHP, Python]
PHP is available

3. Searching Boxed Numbers (Integer) & Null Elements 🔝

When calling marks.contains(54) on an ArrayList<Integer>, Java autoboxes the primitive int into an Integer and compares values via Integer.equals(). Passing null safely checks whether any slot holds a null reference:

ArrayList<Integer> marks = new ArrayList<>(Arrays.asList(55, 54, 60, null));
System.out.println("Contains 54?   " + marks.contains(54));    // true
System.out.println("Contains 99?   " + marks.contains(99));    // false
System.out.println("Contains null? " + marks.contains(null));  // true

Terminal Output:

Contains 54?   true
Contains 99?   false
Contains null? true

4. Using contains() with Custom Domain Objects (Overriding equals) 🔝

Because ArrayList.contains() calls o.equals(element), custom classes must override equals(Object) (and hashCode()). Without an equals() override, Object.equals() only compares memory addresses (==), causing contains(new User(101, "Alice")) to return false:

public class CustomEqualsLookup {
    static class User {
        int id;
        User(int id) { this.id = id; }
        public boolean equals(Object o) { return (o instanceof User) && ((User) o).id == id; }
    }
    public static void main(String[] args) {
        ArrayList<User> users = new ArrayList<>();
        users.add(new User(101));
        System.out.println("Found ID 101? " + users.contains(new User(101)));
    }
}

Terminal Output:

Found ID 101? true

5. Checking Multiple Elements at Once with containsAll() 🔝

Inherited from AbstractCollection, list.containsAll(Collection<?> c) returns true only if every element in c is present in list:

import java.util.Arrays;

ArrayList<String> perms = new ArrayList<>(Arrays.asList("READ", "WRITE", "EXEC"));
boolean hasReadWrite = perms.containsAll(Arrays.asList("READ", "WRITE"));
boolean hasAdmin     = perms.containsAll(Arrays.asList("READ", "ADMIN"));

System.out.println("Has READ+WRITE? " + hasReadWrite);  // true
System.out.println("Has READ+ADMIN? " + hasAdmin);      // false

Terminal Output:

Has READ+WRITE? true
Has READ+ADMIN? false

6. Comparison: ArrayList.contains() vs indexOf() vs HashSet 🔝

Selecting the right lookup mechanism for your collection size:

Lookup Method Complexity Return Value & Best Use Case
list.contains(o) O(n) boolean; best for small lists or occasional membership checks.
list.indexOf(o) O(n) int (0..size-1 or -1); use when you also need the index.
Collections.binarySearch(list, o) O(log n) Requires the ArrayList to be sorted first.
hashSet.contains(o) O(1) avg Best when performing thousands of repeated membership lookups.

7. Production Recipe: Case-Insensitive String Lookup 🔝

Because String.equals() is case-sensitive, tags.contains("java") returns false when the list contains "Java". Use a null-safe helper with equalsIgnoreCase() for case-insensitive matching:

public class CaseInsensitiveCheck {
    public static boolean containsIgnoreCase(ArrayList<String> list, String target) {
        for (String item : list) {
            if (item != null && item.equalsIgnoreCase(target)) return true;
        }
        return false;
    }
    public static void main(String[] args) {
        ArrayList<String> tags = new ArrayList<>(Arrays.asList("Java", "Spring", "SQL"));
        System.out.println("Exact 'java': " + tags.contains("java"));
        System.out.println("IgnoreCase:   " + containsIgnoreCase(tags, "java"));
    }
}

Terminal Output:

Exact 'java': false
IgnoreCase:   true

8. Practical Recipe: Preventing Duplicate Entries with contains() 🔝

Guarding ArrayList.add() with !list.contains(item) keeps small lists duplicate-free:

ArrayList<String> roles = new ArrayList<>();
for (String r : Arrays.asList("EDITOR", "EDITOR", "VIEWER")) {
    if (!roles.contains(r)) roles.add(r);
}
System.out.println("Unique roles: " + roles);

Terminal Output:

Unique roles: [EDITOR, VIEWER]

9. Common Developer Pitfalls & Traps 🔝

Unrelated Type Bug: contains(Object o) Accepts Any Type

Because the parameter is Object rather than generic E, calling marks.contains("54") on an ArrayList<Integer> compiles without any compiler error and silently returns false! Always verify that the search argument matches the list's element type.

Calling ArrayList.contains() Inside a Large Loop (O(n^2) Bottleneck)

Calling list.contains(x) inside a loop of 100,000 items performs up to 10,000,000,000 comparisons. Convert the lookup list to a new HashSet<>(list) before the loop to reduce total lookup time to O(n).

10. Complete Compilable Java Program 🔝

Compile and run this verification class in any Java environment:

public class ArrayListContainsFullDemo {
    public static void main(String[] args) {
        ArrayList<String> items = new ArrayList<>(Arrays.asList("Alpha", "Beta", null));
        if (items.contains("Beta") && items.contains(null) && !items.contains("Gamma")) {
            System.out.println("Check 1 Passed: String and null membership verified.");
        }
        if (items.contains("Beta") == (items.indexOf("Beta") >= 0)) {
            System.out.println("Check 2 Passed: contains(o) matches indexOf(o) >= 0.");
        }
        System.out.println("All ArrayList.contains() verification checks passed!");
    }
}

Terminal Output:

Check 1 Passed: String and null membership verified.
Check 2 Passed: contains(o) matches indexOf(o) >= 0.
All ArrayList.contains() verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

Does ArrayList.contains(null) throw a NullPointerException?

No. ArrayList permits null elements, and list.contains(null) safely scans for a null slot using element == null.

How does ArrayList.contains() work internally?

In the OpenJDK source code, contains(Object o) is a one-line method: return indexOf(o) >= 0;.

Does ArrayList.contains() use hashCode()?

No. Unlike HashSet or HashMap, ArrayList.contains() performs a sequential scan and only invokes equals(Object) on each element.

How can I find how many times an element appears in an ArrayList?

contains() only checks if at least one match exists. To count occurrences, use Collections.frequency(list, target).

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer