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