Java Vector indexOf(Object elem, int index) Method

Java Vector Java Vector


indexOf(Object elem, int index)is in JavaVectorA very useful method provided by the class, used toVectorsearch for a specific element starting from the specified position in the collection, and return the index position of the first occurrence of the element.

Method Syntax

public int indexOf(Object elem, int index)

Parameter Description

Parameter Name Type Description
elem Object The element to be searched for in the Vector
index int The starting index position to begin searching (inclusive of that position), must be non-negative and less than the Vector size

Return Value

Return Value Description
int Returns the index of the first occurrence of the element, or -1 if not found

Method Characteristics

Search Range

This method starts searching from the specifiedindexposition and searches until the end of the Vector.

Element Comparison

Usesequals()method for element comparison, so ensure that the class of the element being searched for correctly implements theequals()method.

Thread Safety

SinceVectoris a thread-safe collection class, theindexOf()method is also thread-safe.

Performance Considerations

This is a linear search method with a time complexity of O(n), not suitable for frequent searches on large-scale data.


Usage Examples

Basic Usage Example

Example

import java.util.Vector;

public class VectorIndexOfExample {
    public static void main(String[] args) {
        // Create a Vector and add elements
        Vector<String> fruits = new Vector<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Apple");
        fruits.add("Grape");
       
        // Search for "Apple" starting from index 1
        int index = fruits.indexOf("Apple", 1);
        System.out.println("'Apple' first occurrence starting from index 1: " + index); // Output 3
       
        // Search for a non-existent element
        int notFound = fruits.indexOf("Mango", 0);
        System.out.println("Search result for 'Mango': " + notFound); // Output -1
    }
}

Edge Case Example

Example

// Test edge cases
Vector<Integer> numbers = new Vector<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(20);
numbers.add(40);

// Starting index equals Vector size
int result1 = numbers.indexOf(20, numbers.size());
System.out.println(result1); // Output -1

// Starting index 0 is equivalent to indexOf(Object elem)
int result2 = numbers.indexOf(20, 0);
System.out.println(result2); // Output 1

// Search for null element
numbers.add(null);
int result3 = numbers.indexOf(null, 3);
System.out.println(result3); // Output 5

Exception Cases

IndexOutOfBoundsException

If the specifiedindexparameter is negative or greater than or equal to the Vector size, anIndexOutOfBoundsException。

Example

try {
    int invalidIndex = fruits.indexOf("Apple", -1); // Throws IndexOutOfBoundsException
} catch (IndexOutOfBoundsException e) {
    System.out.println("Error: " + e.getMessage());
}

Comparison with Related Methods

indexOf(Object elem)

This is theindexOfsimplified version of the method, which starts searching from index 0 by default.

lastIndexOf(Object elem)

Searches elements backwards from the end of the Vector.

lastIndexOf(Object elem, int index)

Searches elements forward from the specified position.


Practical Application Scenarios

Finding Duplicate Elements

Especially useful when you need to find the second or subsequent occurrence position of an element in a Vector.

Segmented Search

In a large Vector, you can search in segments to improve efficiency.

Skipping Processed Parts

When processing Vector elements, you can skip the already-processed parts and continue searching.


Best Practice Recommendations

  1. Check the return value: Always check if the returned index is -1, which indicates the element was not found
  2. Parameter validation: Ensure the passed index parameter is within a valid range
  3. Performance considerations: For frequent search operations, consider using other data structures such as HashSet
  4. null handling: Clearly determine whether null elements need to be handled, because Vector allows storing null values

Summary

Vector.indexOf(Object elem, int index)The method is a practical search tool that extends the basicindexOffunctionality, allowing searches to start from a specified position. Understanding the working principle and edge cases of this method can help developers more effectively handle element search tasks in Vector collections.

Java Vector Java Vector

Other Extensions