Java Vector insertElementAt() Method
insertElementAt() is a method in Java's Vector A method provided by the class, used to insert an element at the specified index position in the vector. This method shifts all elements currently at that position and after it to the right (i.e., their indexes increase by 1).
Method Syntax
public void insertElementAt(E obj, int index)
Parameter Description
E obj: The element to insert; its type must match the Vector's generic typeint index: The position index at which to insert the element (counting from 0)
Method characteristics
1. Index Range
- The valid index range is
0tosize()(inclusive) - If the specified
index = size(), it is equivalent to adding an element at the end (the same asaddElement())
2. Capacity Adjustment
- If the insertion operation causes the Vector's capacity to be insufficient, the Vector automatically expands (the default growth strategy is 2 times the current capacity)
3. Thread safety
- Vector is a thread-safe class, and the
insertElementAt()method is a synchronized method
4. Comparison with ArrayList
- ArrayList has no directly equivalent method, but you can achieve similar functionality through
add(index, element)implementing similar functionality - Vector's method name is longer but more intuitive ("insertElementAt" expresses the operation intent better than "add")
Usage examples
Basic example
Example
import
java.util.Vector
;
public
class
VectorExample
{
public
static
void
main
(
String
[
]
args
)
{
// Create a Vector with an initial capacity of 3
Vector
<
String
fruits
=
new
Vector
<>
(
3
);
// Add initial elements
fruits.
addElement
(
"Apple"
)
;
fruits.
addElement
(
"Banana"
)
;
fruits.
addElement
(
"Orange"
)
;
System
.
out
.
println
(
"Initial Vector: "
fruits
)
;
// Output: Initial Vector: [Apple, Banana, Orange]
// Insert a new element at index 1
fruits.
insertElementAt
(
"Mango"
,
1
)
;
System
.
out
.
println
(
"Vector after insertion: "
fruits
)
;
// Output: Vector after insertion: [Apple, Mango, Banana, Orange]
}
}
Boundary Case Examples
Example
import
java.util.Vector
;
public
class
BoundaryExample
{
public
static
void
main
(
String
[
]
args
)
{
Vector
<
Integer
numbers
=
new
Vector
<>
(
);
numbers.
add
(
10
)
;
numbers.
add
(
20
)
;
try
{
// Try to insert at an invalid index
numbers.
insertElementAt
(
30
,
3
)
;
// Correct: equivalent to addElement(30)
numbers.
insertElementAt
(
40
,
5
)
;
// Throws ArrayIndexOutOfBoundsException
}
catch
(
ArrayIndexOutOfBoundsException
e
)
{
System
.
out
.
println
(
"Caught exception: "
e.
getMessage
(
)
)
;
}
// Insert at the beginning
numbers.
insertElementAt
(
5
,
0
)
;
System
.
out
.
println
(
numbers
)
;
// Output: [5, 10, 20, 30]
}
}
Notes
1. Performance Considerations
- Inserting an element in the middle of a Vector requires shifting all subsequent elements, with a time complexity of O(n)
- Frequent insertion operations may affect performance; consider using data structures better suited for frequent insertion, such as LinkedList
2. Exception Handling
- If the index is out of range (index < 0 || index > size()), a will be thrown
ArrayIndexOutOfBoundsException - It is recommended to check index validity before calling
3. Alternatives
- When thread safety is not needed, consider using ArrayList's
add(int index, E element)Method - Java 8+ can use the Stream API for more flexible element insertion operations
Practical Application Scenarios
1. Dynamic Data Insertion
When data needs to be inserted at a specific position based on certain conditions:
Example
Vector
<
Student
students
=
new
Vector
<>
(
);
// ... add some student data
// Insert a new student at the correct position based on the score
void
insertStudent
(
Student newStudent
)
{
for
(
int
i
=
0
;
i
<
students.
size
(
)
;
i
++
)
{
if
(
newStudent.
getScore
(
)
students.
get
(
i
)
.
getScore
(
)
)
{
students.
insertElementAt
(
newStudent, i
)
;
return
;
}
}
students.
addElement
(
newStudent
)
;
// If the score is the lowest, add to the end
}
2. Priority Queue Implementation
A simple priority queue can be implemented based on Vector and insertElementAt() :
Example
class
PriorityQueue
{
private
Vector
<
Task
tasks
=
new
Vector
<>
(
);
public
void
addTask
(
Task task
)
{
for
(
int
i
=
0
;
i
<
tasks.
size
(
)
;
i
++
)
{
if
(
task.
getPriority
(
)
tasks.
get
(
i
)
.
getPriority
(
)
)
{
tasks.
insertElementAt
(
task, i
)
;
return
;
}
}
tasks.
addElement
(
task
)
;
}
public
Task getNextTask
(
)
{
return
tasks.
isEmpty
(
)
?
null
:
tasks.
remove
(
0
)
;
}
}
Frequently Asked Questions
Q1: insertElementAt() and add(index, element) What is the difference?
insertElementAt()is a Vector-specific method with clearer namingadd(index, element)is a method defined by the List interface, also supported by ArrayList- Functionally the two are equivalent, but Vector's method is synchronized
Q2: Why does the insertion operation affect performance?
- Because the array structure requires shifting all elements after the insertion position
- For example, inserting at the beginning of a Vector with 1000 elements requires shifting 1000 elements
Q3: How can I efficiently insert multiple elements into a Vector?
- If possible, first collect all the elements to insert
- Use
addAll()method to add them in bulk - Or consider using data structures better suited for frequent insertion, such as LinkedList
Summary
Vector.insertElementAt() is a practical method that provides the ability to insert elements at a specific position. Although Vector has been replaced by ArrayList in most modern Java applications, Vector and its methods still have value in scenarios requiring thread safety. Understanding how this method works and its performance characteristics can help developers make more appropriate data structure choices.
Java Vector