Get Enumeration over Java Vector
Last Updated :
11 Jun, 2021
In java, the vector is a typical dynamic array whose size can increase or decrease. While in array the size cannot be changed after declaration. We have to include file import java.util.Vector to use Vector and store values in it. Also, import java.util.Enumeration to use enumeration.
Approach 1: Collection
In the Java Enumeration class, all the listed constants are public, static, and final by default. After creating a Vector the enumeration() method gets Enumeration over Vector.
public static <T> Enumeration <Object> enumeration (Collection <Object> c)
is a member function of public class Collections extends Object.
The enumeration() method returns the enumeration object over the specified Collection and here the specified collection is a Vector. Hereafter getting the enumeration object over a Vector, we will use the hasMoreElements() and nextElement() methods to enumerate through a Vector.
Below is the implementation of the given approach:
Java
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
class GFG {
public static void main(String[] args)
{
Vector<String> vector = new Vector<>();
vector.add( "Let's" );
vector.add( "learn" );
vector.add( "java" );
vector.add( "from" );
vector.add( "GFG" );
System.out.println(
"The elements of the Vector is : " + vector);
Enumeration enumeration
= Collections.enumeration(vector);
System.out.println(
"printing each enumeration constant by enumerating through the Vector:" );
while (enumeration.hasMoreElements()) {
System.out.println(enumeration.nextElement());
}
}
}
|
Output
The elements of the Vector is : [Let's, learn, java, from, GFG]
printing each enumeration constant by enumerating through the Vector:
Let's
learn
java
from
GFG
Time Complexity: O(N), where N is the length of the vector.
Approach 2:
- We will declare the Vector object and then use v.add() to add elements to the vector.
- Use hasMoreElements() and then display the objects using nextElement().
Method use:
- hasMoreElements(): It is used to enumerate if there are more elements.
- nextElements(): It is used to return the next object in enumeration.
Below is the implementation of the given approach:
Java
import java.io.*;
import java.util.Enumeration;
import java.util.Vector;
class GFG {
public static void main(String[] args)
{
Vector<Integer> v = new Vector<Integer>();
v.add( 1 );
v.add( 2 );
v.add( 3 );
v.add( 4 );
Enumeration e = v.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
}
}
|
Time Complexity: O(N), where N is the length of the vector.
Share your thoughts in the comments
Please Login to comment...