Algorithm
-
Define the Enum:
- Declare the enum with constants.
-
Create a Method for Iteration:
- Define a method to iterate over the enum.
-
Use
values()
Method:- Call the
values()
method on the enum to get an array of constants.
- Call the
-
Iterate Over the Array:
- Use a loop (e.g., enhanced for loop) to iterate over the array.
-
Process Each Enum Constant:
- Perform actions for each enum constant inside the loop.
-
Example:
- Output or process each enum constant as needed.
Code Examples
#1 Code Example- Loop through enum using forEach loop
Code -
Java Programming
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
class Main {
public static void main(String[] args) {
System.out.println("Access each enum constants");
// use foreach loop to access each value of enum
for(Size size : Size.values()) {
System.out.print(size + ", ");
}
}
}
Copy The Code &
Try With Live Editor
Output
Access each enum constants
SMALL, MEDIUM, LARGE, EXTRALARGE,
SMALL, MEDIUM, LARGE, EXTRALARGE,
#2 Code Example- Loop through enum using EnumSet Class
Code -
Java Programming
import java.util.EnumSet;
// create an enum
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
class Main {
public static void main(String[] args) {
// create an EnumSet class
// convert the enum Size into the enumset
EnumSet < Size> enumSet = EnumSet.allOf(Size.class);
System.out.println("Elements of EnumSet: ");
// loop through the EnumSet class
for (Size constant : enumSet) {
System.out.print(constant + ", ");
}
}
}
Copy The Code &
Try With Live Editor
Output
Elements of EnumSet:
SMALL, MEDIUM, LARGE, EXTRALARGE,
SMALL, MEDIUM, LARGE, EXTRALARGE,
Demonstration
Java Programing Example to Iterate over enum-DevsEnv