Thursday 8 May 2014

Vector : insertElementAt(E obj, int index)

public synchronized void insertElementAt(E obj, int index)
Inserts element at specific position.

import java.util.*;

class VectorInsertElementAt{
 public static void main(String args[]){
  Vector<Integer> myVector;
  myVector = new Vector<> ();
  
  /*Add Elements to myVector*/
  myVector.add(10);
  myVector.add(11);
  myVector.add(12);
  myVector.add(10);
  myVector.add(12);
  
  System.out.println("Elements in myVector");
  System.out.println(myVector); 
  
  System.out.print("\nInsert 100 at 0th position\n");
  myVector.insertElementAt(100,0);
  
  System.out.println("\nElements in myVector");
  System.out.println(myVector);
 }
}

Output
Elements in myVector
[10, 11, 12, 10, 12]

Insert 100 at 0th position

Elements in myVector
[100, 10, 11, 12, 10, 12]

1. Throws ArrayIndexOutOfBoundsException if the index is out of range
import java.util.*;

class VectorInsertElementAtIndexOut{
 public static void main(String args[]){
  Vector<Integer> myVector;
  myVector = new Vector<> ();
  
  /*Add Elements to myVector*/
  myVector.add(10);
  myVector.add(11);
  myVector.add(12);
  myVector.add(10);
  myVector.add(12);
  
  System.out.println("Elements in myVector");
  System.out.println(myVector); 
  
  System.out.print("\nInsert 100 at 6th position\n");
  myVector.insertElementAt(100,6);
  
  System.out.println("\nElements in myVector");
  System.out.println(myVector);
 }
}

Output
Elements in myVector
[10, 11, 12, 10, 12]

Insert 100 at 6th position
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 > 5
        at java.util.Vector.insertElementAt(Vector.java:594)
        at VectorInsertElementAtIndexOut.main(VectorInsertElementAtIndexOut.java:19)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment