在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);
}
}
以上三種方法都可以遍歷枚舉類型的所有值。你可以根據自己的需求和編程風格選擇合適的方法。