Java Vector.add(int index, E element) Method

 Posted On  | Yashwant Chavan 

In this tutorial, you will learn about Java Vector.add(int index, E element) Method. It inserts the specified element at the specified position in this Vector.

syntax

Inserts the specified element at the specified position in this Vector.

void java.util.Vector.add(int index, E element)

Parameters

index - index at which the specified element is to be inserted.

element - element to be inserted.

Exceptions

throws ArrayIndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

Add element at specific index in Vector

  • Create Vector instances using new Vector().
  • Print existing Vector elements along with index position.
  • Add "Yellow" color at 2nd position.
  • Re-print all the Vector elements.
package com.technicalkeeda.app;

import java.util.Vector;

public class VectorAddElement {
    public static void main(String[] args) {

        Vector < String > colors = new Vector < String > ();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");
        colors.add("Pink");

        for (String color: colors) {
            System.out.println("Vector element index:- " + colors.indexOf(color) + " Element:- " + color);
        }

        colors.add(2, "Yellow");

        System.out.println("\nYellow color added at 2nd position\n");

        for (String color: colors) {
            System.out.println("Vector element index:- " + colors.indexOf(color) + " Element:- " + color);
        }

    }
}

Output

Vector element index:- 0 Element:- Red
Vector element index:- 1 Element:- Green
Vector element index:- 2 Element:- Blue
Vector element index:- 3 Element:- Pink

Yellow color added at 2nd position

Vector element index:- 0 Element:- Red
Vector element index:- 1 Element:- Green
Vector element index:- 2 Element:- Yellow
Vector element index:- 3 Element:- Blue
Vector element index:- 4 Element:- Pink


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0300 seconds.