

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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); }
- Related Questions & Answers
- Difference Between Iterator and Enumeration Interface in Java
- What is the difference between Enumeration interface and enum in Java?
- Enumeration in Java
- Search array of objects in a MongoDB collection?
- Traverse through a HashSet in Java
- Traverse through a HashMap in Java
- Comparing Enumeration Values in Java
- How to sort the documents of a MongoDB collection using java?
- How to iterate the contents of a collection using forEach() in Java?
- How to get the values of a key using the JsonPointer interface in Java?
- Get Enumeration over HashSet in Java
- Duplicating Objects using a Constructor in Java
- Destroying Objects (Garbage Collection) in Python
- Importance of the JsonPatch interface in Java?
- Using the finalize() method in Java Garbage Collection
Advertisements