Java Vector add(int index, Object element) Method
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);
}
}
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
- First, we created a
Vectorobject, and added three elements:"Apple"、"Banana"and"Cherry"。 - Then, we used the
add(1, "Blueberry")method to insert at index 1"Blueberry"。 - Finally, we output
Vectorall elements in the . We can see that"Blueberry"was successfully inserted at the specified position.
Notes
- Index range: The insertion index must be between
0tosize()(including0andsize()).IndexOutOfBoundsExceptionException. - Thread safety:
Vectoris thread-safe, so using the method in a multi-threaded environment isadd(int index, Object element)safe. - Performance considerations: Since
Vectoris implemented based on an array, insertion operations (especially inserting in the middle) may cause the array elements to move, thus affecting performance.
Java Vector