在Java中,可以使用以下方法遍历枚举类型:
- 使用for-each循环遍历枚举类型的所有值:
public enum Weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } public class EnumTraversal { public static void main(String[] args) { for (Weekday day : Weekday.values()) { System.out.println(day); } } }
- 使用EnumSet和Iterator遍历枚举类型的所有值:
import java.util.EnumSet; import java.util.Iterator; public enum Weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } public class EnumTraversal { public static void main(String[] args) { EnumSetweekdays = EnumSet.allOf(Weekday.class); Iterator iterator = weekdays.iterator(); while (iterator.hasNext()) { Weekday day = iterator.next(); System.out.println(day); } } }
- 使用Java 8的Stream API遍历枚举类型的所有值:
import java.util.stream.Stream; public enum Weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } public class EnumTraversal { public static void main(String[] args) { Streamweekdays = Weekday.stream(); weekdays.forEach(System.out::println); } }
以上三种方法都可以遍历枚举类型的所有值。你可以根据自己的需求和编程风格选择合适的方法。