Wednesday, October 8, 2025
HomeLanguagesJavaReplacing Element in Java Vector

Replacing Element in Java Vector

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

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32341 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6709 POSTS0 COMMENTS
Nicole Veronica
11874 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11937 POSTS0 COMMENTS
Shaida Kate Naidoo
6832 POSTS0 COMMENTS
Ted Musemwa
7091 POSTS0 COMMENTS
Thapelo Manthata
6783 POSTS0 COMMENTS
Umr Jansen
6785 POSTS0 COMMENTS