In this tutorial, we will see how to replace Vector elements. We will be using set() method of Vector class to do that.
public E set(int index, E element)
: Replaces the element at the specified position in this Vector with the specified element.
Example
In this example, we are replacing 2nd and 3rd elements of Vector with the new values.
import java.util.Vector; public class ReplaceElements { public static void main(String[] args) { Vector<String> vector = new Vector<String>(); vector.add("Harry"); vector.add("Steve"); vector.add("Vince"); vector.add("David"); vector.add("Matt"); System.out.println("Vector elements before replacement: "); for(int i=0; i < vector.size(); i++) { System.out.println(vector.get(i)); } //Replacing index 1 element vector.set(1,"Mark"); //Replacing index 2 element vector.set(2,"Jack"); System.out.println("Vector elements after replacement: "); for(int i=0; i < vector.size(); i++) { System.out.println(vector.get(i)); } } }
Output:
Vector elements before replacement: Harry Steve Vince David Matt Vector elements after replacement: Harry Mark Jack David Matt
Leave a Reply