Java Vector set(int index, E element) Method Example

We have already seen add(int index, E element) method of java.util.Vector class which will insert the specified element at the specified position in the Vector and shifts the element currently at that position to the right and the new element will added at that index. whereas set(int index, E element) method will replace the element at the specified position in the Vector with the specified element.

Signature

public void set(int index, E element)

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.set(index,element) method.

import java.util.Vector;

public class SetMethodVectorExample 
{
    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.set(1,"Element5");
        
        //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 *