Enum ํด๋์ค(์ด๊ฑฐํ์
)
- ํ์ ๋ ๊ฐ์ธ ์ด๊ฑฐ ์์ ์ค์์ ํ๋์ ์์๋ฅผ ์ ์ฅํ๋ ํ์
- ์ด๊ฑฐ์ฒด๋ฅผ ๋น๊ตํ ๋ ์ค์ ๊ฐ ๋ฟ๋ง ์๋๋ผ ํ์
๊น์ง ์ฒดํฌ
- JDK 1.5์์ ํด๋น ๊ธฐ๋ฅ ์ถ๊ฐ(๊ธฐ์กด์ public class ๋ด final static์ผ๋ก ์ ์ํ๋ ๋ถ๋ถ ๋์ฒด)
- ์ด๊ฑฐ ํ์
์ ์ธํ๋ค๋ฉด ํ์
์ฌ์ฉ ๊ฐ๋ฅ
โก๏ธ ์ด๊ฑฐ ํ์
๋ ํ๋์ ๋ฐ์ดํฐ ํ์
์ด๋ฏ๋ก ๋ณ์๋ฅผ ์ ์ธํ๊ณ ์ฌ์ฉํด์ผ ํจ.
public enum DevType {
MOBILE, FRONTEND, BACKEND, DBA, EMBEDDED
}
public enum Career {
JUNIOR, SENIOR
}
public class Developer {
private String name;
private DevType type;
private Career career;
public Developer(String name, DevType type, Career career) {
this.name = name;
this.type = type;
this.career = career;
}
public void DevInfo() {
System.out.println("์ด๋ฆ : " + name);
System.out.println("์ง์
: " + type);
System.out.println("๊ฒฝ๋ ฅ : " + career);
}
}
public class Main {
public static void main(String[] args) {
Developer dev1 = new Developer("์์ฝฉ๋ฏธ","DevType.BACKEND","Career.JUNIOR");
dev1.devInfo();
}
}
์ด๋ฆ : ์์ฝฉ๋ฏธ
์
๋ฌด : BACKEND
๊ฒฝ๋ ฅ : JUNIOR
์์์ ๊ฐ์ ์ง์ ๋ชปํ๊ฒ ๋ง์ ์ ์์.
์ถํ ๋ฐ์ดํฐ๋ฒ ์ด์ค๋ก ์๋ฃ ์ ๋ฌํ ๊ฒฝ์ฐ ์ฝ๊ฒ ์ ๋ ฌ ํ ์ ์์.
enum Rainbow {
RED, ORANGE, YELLOW, GREEN, BLUE, NAVY, PURPLE
}
values()
- ํด๋น ์ด๊ฑฐ์ฒด์ ๋ชจ๋ ์์๋ฅผ ์ ์ฅํ ๋ฐฐ์ด์ ์์ฑํด์ ๋ฐํ
public class Main{
public static void main(String[] args) {
Rainbow[] arr = Rainbow.values();
for(Rainbow e : arr) System.out.print(e + " ");
RED ORANGE YELLOW GREEN BLUE NAVY PURPLE
valueOf()
- ์ ๋ฌ๋ ๋ฌธ์์ด๊ณผ ์ผ์นํ๋ ํด๋น ์ด๊ฑฐ์ฒด์ ์์๋ฅผ ๋ฐํ
Rainbow rb = Rainbow.valueOf("YELLOW");
System.out.println(rb);
YELLOW
ordinal()
- ํด๋น ์ด๊ฑฐ์ฒด์ ์ ์์์ ์ ์๋ ์์(0๋ถํฐ ์์)๋ฅผ ๋ฐํ
int index = Rainbow.BLUE.ordinal();
System.out.println(index);
4