자바에서는 enum 키워드를 사용해서 열거체를 정의할 수 있다.
enum color {
RED, ORANGE, YELLOW, GREEN, BLUE
}
color.RED
위와 같이 사용한다.
열거체의 첫 번째 상수값은 0부터 설정되며 그다음은 바로앞의 상수값보다 1만큼 증가 된다.
enum color {
RED(1), ORANGE(2), YELLOW(3), GREEN(4), BLUE(5);
private final int value;
color(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
위와 같이 불규칙한 값을 지정하기 위해선 특정값을 저장할 수 있는 인스턴스 변수와 생성자를 추가하고 상수 이름 옆에 괄호를 추가해 값을 명시할 수 있다.
values() 메소드는 열거체의 모든 상수를 저장한 배열을 생성하여 반환한다.
enum color {
RED, ORANGE, YELLOW, GREEN, BLUE;
}
public class EnumStudy {
public static void main(String[] args) {
color[] colors = color.values();
for (color color : colors) {
System.out.println("color = " + color);
}
}
}
valueOf() 메소드는 전달된 문자열과 일치하는 해당 열거체의 상수를 반환한다.
enum Color {
RED, ORANGE, YELLOW, GREEN, BLUE;
}
public class EnumStudy {
public static void main(String[] args) {
Color color = Color.valueOf("RED");
System.out.println("color = " + color);
}
}
ordinal() 메소드는 해당 열거체 상수의 순서를 반환한다.
이때 반환되는 값은 상수값 자체가 이닌 상수가 정의된 순서이다.
enum Color {
RED(4), ORANGE(6), YELLOW(1), GREEN(3), BLUE(9);
private final int value;
Color(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public class EnumStudy {
public static void main(String[] args) {
int a = Color.ORANGE.ordinal();
System.out.println("a = " + a);
}
}