Enum (열거형)

BuZZLightyear·2023년 3월 6일
0

정리

목록 보기
21/47

Enum (열거형)

여러 상수들을 편리하게 선언할 수 있도록 만들어진 자바의 문법 요소

정의 방법

enum 열거형이름 { 상수명1, 상수명2, 상수명3, ...}

ex)

enum Seasons { 
    SPRING, //정수값 0 할당
    SUMMER,  //정수값 1 할당
    FALL, //정수값 2 할당
    WINTER //정수값 3 할당
}

각각의 열거 상수들은 객체이다.
Seasons라는 이름의 열거형은 SPRING, SUMMER, FALL, WINTER 4개의 열거 객체를 포함한다.
각각의 상수들에게 따로 값을 지정해 주지 않아도 자동으로 0부터 시작하는 정수값이 할당되어 상수를 가르키게 된다.

enum Level {
  LOW, // 0
  MEDIUM, // 1
  HIGH // 2
}

public class Main {
  public static void main(String[] args) {
    Level level = Level.MEDIUM;

    switch(level) {
      case LOW:
        System.out.println("낮은 레벨");
        break;
      case MEDIUM:
         System.out.println("중간 레벨");
        break;
      case HIGH:
        System.out.println("높은 레벨");
        break;
    }
  }
}
중간 레벨

열거형에서 사용 가능한 메서드

ex)

enum Level {
  LOW, // 0
  MEDIUM, // 1
  HIGH // 2
}

public class EnumTest {
    public static void main(String[] args) {
        Level level = Level.MEDIUM;

        Level[] allLevels = Level.values();
        for(Level x : allLevels) {
            System.out.printf("%s=%d%n", x.name(), x.ordinal());
        }

        Level findLevel = Level.valueOf("LOW");
        System.out.println(findLevel);
        System.out.println(Level.LOW == Level.valueOf("LOW"));

        switch(level) {
            case LOW:
                System.out.println("낮은 레벨");
                break;
            case MEDIUM:
                System.out.println("중간 레벨");
                break;
            case HIGH:
                System.out.println("높은 레벨");
                break;
        }
    }
}
LOW=0
MEDIUM=1
HIGH=2
LOW
true
중간 레벨
enum Seasons {
    SPRING, SUMMER, FALL, WINTER
}
public class Main {
    public static void main(String[] args) {
        int seasons = Seasons.WINTER.compareTo(Seasons.SUMMER);
        System.out.println(seasons);
        int seasons2 = Seasons.WINTER.ordinal();
        System.out.println(seasons2);
    }
}
2
3
profile
버즈라이트이어

0개의 댓글