Java Vector insertElementAt() Method
insertElementAt()is, in Java,Vectora method provided by the class, used to insert an element at the specified index position in the vector.
Method Syntax
public void insertElementAt(E obj, int index)
Parameter Description
E obj: The element to be inserted, with a type consistent with the Vector's generic type.int index: The index position where the element is to be inserted (counting from 0).
Method Features
1. Index Range
- The valid index range is
0tosize()(inclusive) - If you specify
index = size(), it is equivalent to adding an element at the end (with the sameaddElement()effect)
2. Capacity Adjustment
- If an insertion operation causes the Vector's capacity to be insufficient, the Vector will automatically expand (the default growth strategy is doubling the current capacity).
3. Thread Safety
- Vector is a thread-safe class, and
insertElementAt()the method is a synchronized method.
4. Comparison with ArrayList
- ArrayList does not have a directly equivalent method, but it can be implemented through
add(index, element)to implement 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]
}
}
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]
}
}
Edge Case Example
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 {
// Attempt 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]
}
}
public class BoundaryExample {
public static void main(String[] args) {
Vector<Integer> numbers = new Vector<>();
numbers.add(10);
numbers.add(20);
try {
// Attempt 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 LinkedList or other data structures better suited for frequent insertion.
2. Exception Handling
- If the index is out of range (index < 0 || index > size()), it will throw
ArrayIndexOutOfBoundsException - It is recommended to check the validity of the index before calling.
3. Alternatives
- For situations that do not require thread safety, you may 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 you need to insert data at a specific position based on certain conditions:
Example
Vector<Student> students = new Vector<>();
// ... Add some student data
// Insert the new student into the correct position based on 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
}
// ... Add some student data
// Insert the new student into the correct position based on 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
It can be based on Vector andinsertElementAt()to implement a simple priority queue:
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);
}
}
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);
}
}
FAQ
Q1: insertElementAt()andadd(index, element)What is the difference?
insertElementAt()It is a Vector-specific method with a clearer name.add(index, element)It is a method defined by the List interface, and ArrayList also supports it.- Functionally the two are equivalent, but Vector's method is synchronized.
Q2: Why does the insertion operation affect performance?
- Because the array structure needs to move all elements after the insertion position.
- For example, inserting at the beginning of a Vector with 1000 elements requires moving 1000 elements.
Q3: How to efficiently insert multiple elements into a Vector?
- If possible, first collect all the elements to be inserted.
- Use the
addAll()method to add them in bulk. - Or consider using LinkedList or other data structures better suited for frequent insertion.
Summary
Vector.insertElementAt()It is a practical method that provides the ability to insert an element at a specific position. Although Vector has been replaced by ArrayList in most modern Java applications, Vector and its methods still retain their value in scenarios requiring thread safety. Understanding the working principle and performance characteristics of this method can help developers make more appropriate data structure choices.
Java Vector