Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Vector add(int index, Object element) Method

Java Vector add(int index, Object element) Method

Java Vector Java Vector

In Java programming,Vector is a dynamic array that can automatically resize as needed.Vector The class provides multiple methods to operate on its elements, among which the add(int index, Object element) method is used to insert an element at a specified position. This article introduces in detail the add(int index, Object element) method's usage and 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

Return Value

This method has no return value (void type).


Example

Here is a simple example demonstrating how to use the add(int index, Object element) The method inserts a new entry in the user profile table in the Vector to insert an element.

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 a Vector object, and added three elements:"Apple", "Banana" and "Cherry".
  2. Then, we use the add(1, "Blueberry") The method inserts at index 1 of the "Blueberry".
  3. Finally, we output the contents of the Vector all elements, and you can see that "Blueberry" has been successfully inserted at the specified position.

Notes

  1. Index Range: The insertion index must be between 0 to size() (inclusive 0 and size()). If the index exceeds this range, a IndexOutOfBoundsException exception.
  2. Thread Safety: Vector is thread-safe, so using the add(int index, Object element) method in a multithreaded environment is safe.
  3. Performance considerations: Because Vector is implemented based on arrays, insertion operations (especially inserting in the middle) may cause array elements to shift, affecting performance.

Java Vector Java Vector