beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Replace Vector elements using index – Java example

By Chaitanya Singh | Filed Under: Java Collections

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 Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap