Enum
- enumearation : 셈, 열거
- 열거형이란 서로 연관된 상수들의 집합
- 서로 관련있는 상수들끼리 모아 상수들을 정의하는 것
- 갖는 값뿐만 아니라 타입까지 관리하여 논리적 오류를 줄임
(값이 같아도 열거형 타입이 다르면 false, 비교할 때는 "==" 사용)
- static, final이 내장되어 있어 한번 정의된 값을 바꿀 수 없으며 int형의 변수처럼 switch문에서 사용가능
예시
- enum 클래스에 열거형과 code, msg를 선언한 뒤 생성자를 만듦.
- 각각에 대한 getter 만듦
public enum ExceptionMessage
ERROR1("000", "ERROR1이 발생하였습니다."),
ERROR2("001", "ERROR2이 발생하였습니다."),
ERROR3("002", "ERROR3이 발생하였습니다."),
ERROR4("003", "ERROR4이 발생하였습니다."),
ERROR5("004", "ERROR5이 발생하였습니다.");
private String codel;
private String msg;
private ExceptionMessage(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getMsg() {
return this.msg;
}
public String getCode() {
return this.code;
}
}
index로 enum 값을 가져오고 싶을 때
public enum Countries {
TEXAS,
FLORIDA,
OKLAHOMA,
KENTUCKY;
private static Countries[] list = Countries.values();
public static Countries getCountry(int i) {
return list[i];
}
public static int listGetLastIndex() {
return list.length - 1;
}
}
enum 정의와 속성
enum의 뿌리
enum에 index