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
  • 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

Enjoyed this post? Try these related posts

  1. Java – Convert Vector to List example
  2. Java – Remove first and last element from LinkedList example
  3. Java ArrayList isEmpty() Method example
  4. How to get sub list of Vector example in java
  5. How to get sublist of an ArrayList with example
  6. Java ArrayList addAll(int index, Collection c) Method example

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 – 2021 BeginnersBook . Privacy Policy . Sitemap