This example shows how to insert the element at the beginning of the Vector in Java. This example also shows how to insert an element at any index in Vector using the add and insertElementAt methods.
How to insert an element at the beginning of the Vector in Java (at the front)?
The Vector add
method inserts the specified element at the specified index in this vector object.
1 |
public void add(int index, E element) |
It inserts the element at the given index of the vector object. This method shifts the existing elements at and after the specified index to the right by adding 1 to their indices.
To insert the element at the beginning of the Vector object, we need to pass the index as 0 as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Vector; public class VectorInsertElementAtBeginning { public static void main(String[] args) { Vector<String> vColors = new Vector<String>(); vColors.add("Black"); vColors.add("Orange"); vColors.add("Yellow"); /* * To insert element at the front of the Vector object, use * the overloaded add method with index parameter and * pass index as 0 */ //this will insert "Red" at the beginning vColors.add(0, "Red"); System.out.println("Vector contains: " + vColors); } } |
Output
1 |
Vector contains: [Red, Black, Orange, Yellow] |
Important Note:
There are two versions of the add
method in the Vector class, one is with the index parameter and another is without the index parameter. The add
method without the index parameter always appends the elements at the end of the Vector object.
We can also use the Vector insertElementAt
method instead of the above given add
method to insert the element at the front of the vector object.
1 |
public void insertElementAt(E element, int index) |
The insertElementAt
method is identical to the add
method in functionality and inserts the specified element at the given index of the vector object.
1 2 3 4 5 6 7 8 9 |
Vector<String> vColors = new Vector<String>(); vColors.add("Black"); vColors.add("Orange"); vColors.add("Yellow"); vColors.insertElementAt("Red", 0); System.out.println("Vector contains: " + vColors); |
Output
1 |
Vector contains: [Red, Black, Orange, Yellow] |
Note: The sequence of parameters of the insertElementAt
method is in the reverse order as compared to the add
method. The add
method has the index as the first parameter and the element as the second parameter, while the insertElementAt
method has the element as the first parameter and the index as the second parameter.
This example is a part of the Vector in Java Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 Vector Documentation