Vector

Remove Vector elements using index example

In this example we shall show you how to remove elements from a Vector using index. To remove an element from a Vector using index one should perform the following steps:

  • Create a new Vector.
  • Populate the vector with elements, with add(E e) API method of Vector.
  • Remove an element from the Vector. Invoke remove(int index) API method of Vector, with an index as parameter. The method removes the element at the specified position in this Vector and shifts any subsequent elements to the left (subtracts one from their indices). It returns the element that was removed from the Vector,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;
 
import java.util.Vector;
 
public class RemoveElementFromVectorIndex {
 
  public static void main(String[] args) {
 
    // Create a Vector and populate it with elements
    Vector vector = new Vector();
    vector.add("element_1");
    vector.add("element_2");
    vector.add("element_3");
 
    /*

To remove an element from the specified index of Vector use

Object remove(int index) method.

The method returns a reference to the element that was removed.
    */
    Object obj = vector.remove(2);
    System.out.println(obj + " is removed from Vector");
 
    System.out.println("Elements in Vector :");
    for(int i=0; i < vector.size(); i++)

System.out.println(vector.get(i));
 
  }
}

Output:

element_3 is removed from Vector
Elements in Vector :
element_1
element_2

 
This was an example of how to remove elements from a Vector using index in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button