Vector

Add element to specified index of Vector example

In this example we shall show you how to add an element to a specified index of a Vector. The Vector API provides both add(E e) and add(int index, E element) methods, to add an element either at the end of the Vector or at a specified index of a Vector. To add an element to a specified index of a Vector one should perform the following steps:

  • Create a new Vector.
  • Populate the vector with elements, with add(E e) API method of Vector.
  • Invoke add(int index, E element) API method of Vector, to add an element at the specified index of the Vector,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;
 
import java.util.Vector;
 
public class AddElementToSpecifiedIndexVector {
 
  public static void main(String[] args) {

    // Create a Vector and populate it with elements
    Vector vector = new Vector();
    vector.add("element_1");
    vector.add("element_2");
    vector.add("element_3");
 
    /*

To add an element at the specified index of Vector use

void add(int index, Object obj) method. This method does 

NOT overwrite the element previously at the specified index 

in the vector rather it shifts the existing elements to right 

side increasing the vector size by 1.
    */
    vector.add(1,"new_element");
 
    System.out.println("Elements in Vector : ");
    for(int i=0; i < vector.size(); i++)

System.out.println(vector.get(i));

  }
}

Output:

Elements in Vector : 
element_1
new_element
element_2
element_3

 
This was an example of how to add an element to a specified index of a Vector in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button