Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

vector
communitycreator

How to add an element at a specific index in Vector

Programming Bytes

We can use the add(index, element) method to add an element at a specific index. This will add the element to the passed index. When calling add(index, element), the element is added at the index, and the elements already present at the index are moved one step right.

Vector is a growable array of objects. Elements are mapped to an index.

Syntax

public void add(int index, E element);

The index argument denotes the index at which the new element should be added. The index should be greater than or equal to 0 and less than the size of the vector. Any other index value will result in: ArrayIndexOutOfBoundsException.

index >= 0 && index < vectorSize

Code

import java.util.Vector;
class VectorAddExample  {
    public static void main( String args[] ) {
        // Creating Vector
        Vector<Integer> vector = new Vector<>();

        // add elememts 
        vector.add(1);
        vector.add(3);

        // Print vector
        System.out.println("The Vector is: " + vector);
  
        int index = 1;
        int element = 2;
        System.out.println("Adding element :" + element + " at index :" +index);
        vector.add(index, element);
  
        // Printing the new vector
        System.out.println("The Vector is: " + vector);
    }
}

Explanation

In the code above, we create a Vector object and add elements 1,3 to the vector object. Then, we use the code below to add the element 2 to the index 1. Now, the vector will be 1,2,3.

vector.add(1, 2);

RELATED TAGS

vector
communitycreator
RELATED COURSES

View all Courses

Keep Exploring