Open In App

Replacing Element in Java Vector

Last Updated : 11 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

To replace an element in Java Vector, set() method of java.util.Vector class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element. The index of a Vector is zero-based. So, to replace the first element, 0 should be the index passed as parameter.

Declaration:

 public Object set(int index, Object element)

Return Value: 

The element which is at the specified index

Exception Throws:

IndexOutOfBoundsException 
when the index is out of range 
i.e, index < 0 or index >= size()

Implementation:

Java




// Replacing Element in Java Vector
import java.util.Vector;
public class Sias {
    public static void main(String args[])
    {
        try {
  
            // create a instance vector
            Vector<Integer> vector = new Vector<>();
  
            // insert the values in vector
            vector.add(1);
            vector.add(2);
            vector.add(3);
            vector.add(4);
            vector.add(5);
  
            // display the vector
            System.out.println("original vector : "
                               + vector);
  
            // call set() and replace 2 index value
            vector.set(2, 10);
  
            // display vector after replacing value
            System.out.println("after replace the value : "
                               + vector);
            // call set() and replace 9th index value
            // which is exception as arrayoutofbound
            vector.set(9, 91);
  
            // display vector after replacing value
            System.out.println("after replace the value : "
                               + vector);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


Output

original vector : [1, 2, 3, 4, 5]
after replace the value : [1, 2, 10, 4, 5]
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 9

Time Complexity: O(n), where n is the length of the vector



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads