使用数组和 EnumSet 迭代枚举元素的 Java 程序

要理解此示例,您应该具备以下 Java 编程的知识:

示例 1:使用 forEach 循环遍历枚举

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 + ", ");
    }
  }
 }

输出 1

Access each enum constants
SMALL, MEDIUM, LARGE, EXTRALARGE,

在上面的例子中,我们有一个名为 Size 的枚举. 注意这一行,

Size.values()

在这里,该 values() 方法将枚举常量转换为数组。然后我们使用 forEach 循环访问枚举的每个元素。

示例 2:使用 EnumSet 类循环遍历枚举

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 + ", ");
    }

  }
 }

输出

Elements of EnumSet:
SMALL, MEDIUM, LARGE, EXTRALARGE,

在这里,我们使用了 EnumSet 类的 allOf() 方法将 Size 转为 EnumSet 对象. 然后我们使用 forEach 循环访问 EnumSet 类的每个元素 。