Friday 9 May 2014

Vector : setElementAt (E obj, int index) : Replace Element at index

public synchronized void setElementAt(E obj, int index)
Replaces the element at the specified position in this Vector with the specified element.

import java.util.*;

class VectorSetElementAt{
 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(13);
  
  System.out.println("Elements in myVector ");
  System.out.println(myVector);
  
  System.out.println("\nReplacing value at index 1 to 0");
  myVector.setElementAt(0, 1);
  
  System.out.println("\nElements in myVector ");
  System.out.println(myVector);
 }
}

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

Replacing value at index 1 to 0

Elements in myVector
[10, 0, 12, 13]

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

class VectorSetElementAtIndexOut{
 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(13);
  
  System.out.println("Elements in myVector ");
  System.out.println(myVector);
  
  System.out.println("\nReplacing value at index -1 to 0");
  myVector.setElementAt(0, -1);
 }
}

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

Replacing value at index -1 to 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
        at java.util.Vector.setElementAt(Vector.java:529)
        at VectorSetElementAtIndexOut.main(VectorSetElementAtIndexOut.java:18)

 
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment