Java의 열거형은 명명된 상수 그룹을 나타내며 다음 구문을 사용하여 열거형을 만들 수 있습니다. -
enum Days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
} values() 메서드를 사용하여 열거형의 내용을 검색할 수 있습니다. 이 메서드는 모든 값을 포함하는 배열을 반환합니다. 배열을 얻으면 for 루프를 사용하여 반복할 수 있습니다.
예시
public class IterateEnum{
public static void main(String args[]) {
Days days[] = Days.values();
System.out.println("Contents of the enum are: ");
//Iterating enum using the for loop
for(Days day: days) {
System.out.println(day);
}
}
} 출력
Contents of the enum are: SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY
예시
enum Vehicles {
//Declaring the constants of the enum
ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER;
int i; //Instance variable
Vehicles() { //constructor
}
public void enumMethod() { //method
System.out.println("Current value: "+Vehicles.this);
}
}
public class Sam{
public static void main(String args[]) {
Vehicles vehicles[] = Vehicles.values();
for(Vehicles veh: vehicles) {
System.out.println(veh);
}
vehicles[3].enumMethod();
}
} 출력
ACTIVA125 ACTIVA5G ACCESS125 VESPA TVSJUPITER Current value: VESPA