Java Vector add(int index, Object element) Method

Java Vector Java Vector

In Java programming,Vectoris a dynamic array that can automatically adjust its size as needed.VectorThe class provides multiple methods to manipulate its elements, whereadd(int index, Object element)method is used to insert an element at a specified position. This article will detailadd(int index, Object element)the usage of the method and its related concepts.


Method Definition

add(int index, Object element)The definition of the method is as follows:

public void add(int index, Object element)

Parameter Description

  • index: The index of the position at which the element is to be inserted. The index starts from 0, representing the position of the first element.
  • element: The element to be inserted, which can be any object.

Return Value

This method has no return value (voidtype).


Example

The following is a simple example that demonstrates how to useadd(int index, Object element)method toVectorinsert elements.

Example

import java.util.Vector;

public class VectorExample {
    public static void main(String[] args) {
        // Create a Vector object
        Vector<String> vector = new Vector<>();

        // Add elements to the Vector
        vector.add("Apple");
        vector.add("Banana");
        vector.add("Cherry");

        // Insert "Blueberry" at index 1
        vector.add(1, "Blueberry");

        // Output the elements in the Vector
        System.out.println("Vector elements: " + vector);
    }
}

Output Result

Vector elements: [Apple, Blueberry, Banana, Cherry]

Code Explanation

  1. First, we created aVectorobject, and added three elements:"Apple"、"Banana"and"Cherry"。
  2. Then, we used theadd(1, "Blueberry")method to insert at index 1"Blueberry"。
  3. Finally, we outputVectorall elements in the . We can see that"Blueberry"was successfully inserted at the specified position.

Notes

  1. Index range: The insertion index must be between0tosize()(including0andsize()).IndexOutOfBoundsExceptionException.
  2. Thread safety: Vectoris thread-safe, so using the method in a multi-threaded environment isadd(int index, Object element)safe.
  3. Performance considerations: SinceVectoris implemented based on an array, insertion operations (especially inserting in the middle) may cause the array elements to move, thus affecting performance.

Java Vector Java Vector

Other extensions