Java Vector removeElement() removeElementAt() Methods Tutorial

In this section, we will learn what the Vector removeElement(), removeElementAt() methods are and how to use them in Java.

What is Java Vector removeElement() Method?

The Java Vector removeElement() method is used to remove an element from a vector object.

Note: the method only removes the first occurrence of the element we’ve specified as its argument.

Java Vector removeElement() Method Syntax:

public boolean removeElement(Object obj)

removeElement() Method Parameters:

The method takes one argument and that is the element we want to remove from the target vector object.

removeElement() Method Return Value:

The return value of this method is of type Boolean.

If the target element (the argument) was found in the vector object and got removed, the return value of this method becomes true which means a successful operation. Otherwise, the value false will return instead.

removeElement() Method Exceptions:

The method does not throw an exception.

Example: using Vector removeElement() method

import java.util.Vector; 
public class Main {

    public static void main(String[] args){
        
      Vector <Integer> vector = new Vector<>();
      vector.addElement(1);
      vector.addElement(2);
      vector.addElement(3);
      vector.addElement(4);
      vector.addElement(5);

      vector.removeElement(5);
      for(int i: vector){
         System.out.println(i);
      }
    }
}

Output:

1

2

3

4

What is Java Vector removeElementAt() Method?

The Java Vector removeElementAt() method is used to remove an element of a vector object at a specific index.

For example, you have a vector object with 10 elements and want to remove the element in the index number 5, then this method can help you with.

Java Vector removeElementAt() Method Syntax:

public void removeElementAt(int index)

removeElementAt() Method Parameters:

The method takes one argument and that is the index number where we want to remove the element that is there.

removeElementAt() Method Return Value:

The return value of this method is void.

removeElementAt() Method Exceptions:

IndexOutOfBoundsException: We get this exception if we put an index number that is out of the range in the target vector object.

Example: using Vector removeElementAt() method

import java.util.Vector; 
public class Main {

    public static void main(String[] args){
        
      Vector <Integer> vector = new Vector<>();
      vector.addElement(1);
      vector.addElement(2);
      vector.addElement(3);
      vector.addElement(4);
      vector.addElement(5);

      vector.removeElementAt(3);
      for(int i: vector){
         System.out.println(i);
      }
    }
}

Output:

1

2

3

5
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies