
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Traverse a Collection of Objects Using the Enumeration Interface in Java
All the elements in a collection of objects can be traversed using the Enumeration interface. The method hasMoreElements( ) returns true if there are more elements to be enumerated and false if there are no more elements to be enumerated. The method nextElement( ) returns the next object in the enumeration.
A program that demonstrates this is given as follows −
Example
import java.util.Enumeration; import java.util.Vector; public class Demo { public static void main(String args[]) throws Exception { Vector vec = new Vector(); vec.add("John"); vec.add("Gary"); vec.add("Susan"); vec.add("Mike"); vec.add("Angela"); Enumeration enumeration = vec.elements(); System.out.println("The vector elements are:"); while (enumeration.hasMoreElements()) { Object obj = enumeration.nextElement(); System.out.println(obj); } } }
Output
The vector elements are: John Gary Susan Mike Angela
Now let us understand the above program.
The Vector is created and Vector.add() is used to add the elements to the Vector. Then the vector elements are displayed using the enumeration interface. A code snippet which demonstrates this is as follows −
Vector vec = new Vector(); vec.add("John"); vec.add("Gary"); vec.add("Susan"); vec.add("Mike"); vec.add("Angela"); Enumeration enumeration = vec.elements(); System.out.println("The vector elements are:"); while (enumeration.hasMoreElements()) { Object obj = enumeration.nextElement(); System.out.println(obj); }
Advertisements