English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to traverse enumeration elements in Java by converting enumeration to an array and enumeration set.
To understand this example, you should know the followingJava programmingTopic:
enum Size { SMALL, MEDIUM, LARGE, EXTRALARGE } class Main { public static void main(String[] args) { System.out.println("Access each enumeration constant"); // Use the foreach loop to access each value of the enumeration for(Size size : Size.values()) { System.out.print(size + ", "); } } }
Output1
Access each enumeration constant SMALL, MEDIUM, LARGE, EXTRALARGE,
In the above example, we have an enumeration named Size. Note the expression
Size.values()
Here, the values() method converts enumeration constants to an array of Size type. Then, we use the forEach loop to access each element of the enumeration.
import java.util.EnumSet; //Create an enumeration enum Size { SMALL, MEDIUM, LARGE, EXTRALARGE } class Main { public static void main(String[] args) { //Create an EnumSet class //Convert enum Size to EnumSet EnumSet<Size> enumSet = EnumSet.allOf(Size.class); System.out.println("Elements of EnumSet: "); //Traverse EnumSet class for (Size constant : enumSet) { System.out.print(constant + ", "); } } }
Output Result
Elements of EnumSet: SMALL, MEDIUM, LARGE, EXTRALARGE,
Here, we use the allOf() method to create an EnumSet class from the enum Size. Then we use the forEach loop to access each element of the enumset class.