Wednesday, November 20, 2024
Google search engine
HomeLanguagesJavaEnumeration nextElement() Method in Java with Examples

Enumeration nextElement() Method in Java with Examples

An object that implements the Enumeration interface generates a series of elements, one at a time. The nextElement() method of Enumeration used to return the next element of this enumeration if this enumeration object has at least one more element to provide.This method is used to get elements from the enumeration. Syntax:

E nextElement()

Parameters: This method accepts nothing. Return value: This method returns true the next element of this enumeration. Exception: This method throws NoSuchElementException if no more elements exist. Below programs illustrate nextElement() method: Program 1: 

Java




// Java program to demonstrate
// Enumeration.nextElement() method
 
import java.util.*;
 
public class GFG {
 
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args)
    {
 
        // create a Enumeration and vector object
        Enumeration<Integer> company;
        Vector<Integer> employees = new Vector<Integer>();
 
        // add values to employees
        employees.add(1001);
        employees.add(2001);
        employees.add(3001);
        employees.add(4001);
        company = employees.elements();
 
        while (company.hasMoreElements()) {
            // get elements using nextElement()
            System.out.println("Emp ID = "
                               + company.nextElement());
        }
    }
}


Output:

Emp ID = 1001
Emp ID = 2001
Emp ID = 3001
Emp ID = 4001

Program 2: 

Java




// Java program to demonstrate
// Enumeration.nextElement() method
 
import java.util.*;
 
public class GFG {
 
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args)
    {
 
        // create a Enumeration and vector object
        Enumeration<String> Users;
        Vector<String> user = new Vector<String>();
 
        // add Users
        user.add("Aman Singh");
        user.add("Raunak Singh");
        user.add("Siddhant Gupta");
        Users = user.elements();
 
        while (Users.hasMoreElements()) {
            // get elements using nextElement()
            System.out.println(Users.nextElement());
        }
    }
}


Output:

Aman Singh
Raunak Singh
Siddhant Gupta

References: https://docs.oracle.com/javase/10/docs/api/java/util/Enumeration.html#nextElement()

RELATED ARTICLES

Most Popular

Recent Comments