Java Vector add(int index, Object element) Method
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
- index: The position index at which to insert the element. The index starts at 0, which represents the position of the first element.
- element: The element to insert; it can be any object.
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
- First, we created a
Vectorobject, and added three elements:"Apple","Banana"and"Cherry". - Then, we use the
add(1, "Blueberry")The method inserts at index 1 of the"Blueberry". - Finally, we output the contents of the
Vectorall elements, and you can see that"Blueberry"has been successfully inserted at the specified position.
Notes
- Index Range: The insertion index must be between
0tosize()(inclusive0andsize()). If the index exceeds this range, aIndexOutOfBoundsExceptionexception. - Thread Safety:
Vectoris thread-safe, so using theadd(int index, Object element)method in a multithreaded environment is safe. - Performance considerations: Because
Vectoris implemented based on arrays, insertion operations (especially inserting in the middle) may cause array elements to shift, affecting performance.
Java Vector