Java Vector contains() Method Explained in Detail

Java Vector Java Vector


containsThe method isVectora very useful method provided by the class, used to check whether the collection contains the specified element.

Syntax Format

public boolean contains(Object o)

Parameter Description

  • o: The element to check whether it exists in the collection

Return Value

  • true: If the collection contains the specified element
  • false: If the collection does not contain the specified element

How the contains Method Works

containsThe method, by traversingVectorall elements in, and usingequalsthe method to compare each element with the target element for equality. When the first matching element is found, the method immediately returnstrue; if no matching element is found after traversing all elements, it returnsfalse。

Underlying Implementation

In the Java source code,Vectorofcontainsthe method actually callsindexOfmethod:

Example

public boolean contains(Object o) {
    return indexOf(o, 0) >= 0;
}

indexOfThe method searches for the element starting from the specified position, and returns its index if found, otherwise returns -1.


Usage Example

Let's take a look through a few practical examples atcontainsthe usage of the method.

Example 1: Basic Usage

Example

Vector<String> colors = new Vector<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");

System.out.println(colors.contains("Green"));  // Output: true
System.out.println(colors.contains("Yellow")); // Output: false

Example 2: Custom Objects

When using custom objects, you need to correctly implementequalsmethod, otherwisecontainsthe method may not work as expected.

Example

class Person {
    String name;
    int age;
   
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
   
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Person person = (Person) obj;
        return age == person.age && Objects.equals(name, person.name);
    }
   
    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

public class Main {
    public static void main(String[] args) {
        Vector<Person> people = new Vector<>();
        people.add(new Person("Alice", 25));
        people.add(new Person("Bob", 30));
       
        System.out.println(people.contains(new Person("Alice", 25)));  // Output: true
        System.out.println(people.contains(new Person("Charlie", 35))); // Output: false
    }
}

Performance Considerations

SinceVectoris implemented based on an array,containsthe time complexity of the method is O(n), i.e., linear time. This means asVectorthe number of elements in it increases, the search time will also increase linearly.

Optimization Suggestions

If you need to frequently perform containment checks and the collection is large, you can consider the following optimization options:

  1. Use HashSet: If order is not important and elements are unique,HashSetofcontainsthe average time complexity of the method is O(1).

    Example

    HashSet<String> colors = new HashSet<>();
    colors.add("Red");
    colors.add("Green");
    System.out.println(colors.contains("Green")); // Fast lookup
  2. Sort and then use binary search: IfVectorit is sorted, you can first useCollections.sort()to sort, then useCollections.binarySearch()to perform the search, with a time complexity of O(log n).

    Example

    Vector<String> sortedColors = new Vector<>();
    sortedColors.add("Blue");
    sortedColors.add("Green");
    sortedColors.add("Red");
    Collections.sort(sortedColors);
    int index = Collections.binarySearch(sortedColors, "Green");
    System.out.println(index >= 0); // Output: true

Frequently Asked Questions

Q1: Is the contains method case-sensitive?

For strings,containsthe method is case-sensitive because it relies onequalsmethod:

Example

Vector<String> words = new Vector<>();
words.add("Hello");
System.out.println(words.contains("hello")); // Output: false

If you need a case-insensitive check, you can implement it like this:

Example

boolean containsIgnoreCase(Vector<String> vector, String target) {
    for (String s : vector) {
        if (s.equalsIgnoreCase(target)) {
            return true;
        }
    }
    return false;
}

Q2: Can the contains method check for null values?

Yes,Vectorit allows storingnullvalues, andcontainsthe method can checknull:

Example

Vector<String> items = new Vector<>();
items.add(null);
System.out.println(items.contains(null)); // Output: true

Q3: What is the difference between the contains method and the indexOf method?

  • contains: Returns a boolean value, only tells you whether the element exists
  • indexOf: Returns the index position of the element, or -1 if it does not exist

Example

Vector<String> fruits = new Vector<>();
fruits.add("Apple");
fruits.add("Banana");

System.out.println(fruits.contains("Banana")); // Output: true
System.out.println(fruits.indexOf("Banana"));  // Output: 1

Summary

VectorofcontainsThe method is a simple but powerful tool for checking whether a specific element exists in the collection. Understanding its working principle and performance characteristics is very important for writing efficient Java code. Remember the following points:

  1. containsThe method relies onequalsthe method for element comparison
  2. For custom objects, you must correctly implementequalsandhashCodethe method
  3. containsThe time complexity of the method is O(n); for large collections, you may need to consider more efficient data structures.
  4. VectorIt is thread-safe, but if thread safety is not needed,ArrayListmay be a better choice

By reasonably usingcontainsthe method, you can manage and query the data in the collection more effectively.

Java Vector Java Vector

Other Extensions