Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Replacing Element in Java Vector

  • Difficulty Level : Medium
  • Last Updated : 11 Dec, 2020

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.


 public Object set(int index, Object element)

Return Value: 

The element which is at the specified index

Exception Throws:

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



// 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
            // 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) {
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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!