Java Vector setElementAt(E obj,int index) Example

We have already seen set(int index, E element) method of java.util.Vector class will replace the element at the specified position in the Vector with the specified element, sameway setElementAt(E obj,int index) method will set the element at the specified index of this vector to be the specified object.The previous element at that position will be discarded.

Signature

public void setElementAt(E obj,int index)

This method replaces the element at the specified position in the Vector with the specified element and will throw “java.lang.ArrayIndexOutOfBoundsException”  if the index is out of range.

Example

The following example shows the usage of java.util.Vector.setElementAt(obj,index) method.

import java.util.Vector;

public class SetElementAtMethodVectorExample 
{
    public static void main(String args[])
    {
     // create an empty Vector
        Vector vector1 = new Vector();
        
        // use add() method to add elements to the Vector
        vector1.add("Element1");
        vector1.add("Element2");
        vector1.add("Element3");
        vector1.add("Element4");
        
        //Printing the elements of the Vector
        System.out.println("**Elements of the Vector1 before set method**");
        for(String temp:vector1)
        {
            System.out.println(temp);
        }
        
        vector1.setElementAt("Element5",1);
        
        //Printing the elements of the Vector
        System.out.println("**Elements of the Vector1 after set method**");
        for(String temp:vector1)
        {
            System.out.println(temp);
        }
    }
}

Output

**Elements of the Vector1 before set method**
Element1
Element2
Element3
Element4
**Elements of the Vector1 after set method**
Element1
Element5
Element3
Element4

Leave a Reply

Your email address will not be published. Required fields are marked *