[11] Java - Enum

21715 단어 Java-BasicJava-Basic

학습할 것 (필수)

  • enum 정의하는 방법
  • enum이 제공하는 메소드 (values()와 valueOf())
  • java.lang.Enum
  • EnumSet

enum 정의하는 방법


열거체(enumeration type)

C언어와 C++에서는 열거체를 사용할 수 있지만, JDK 1.5 이전의 자바에서는 열거체를 사용할 수 없었습니다.

하지만 JDK 1.5부터는 C언어의 열거체보다 더욱 향상된 성능의 열거체를 정의한 Enum 클래스를 사용할 수 있습니다.

이와 같은 자바의 열거체는 다음과 같은 장점을 가집니다.

  1. 열거체를 비교할 때 실제 값뿐만 아니라 타입까지도 체크합니다.

  2. 열거체의 상숫값이 재정의되더라도 다시 컴파일할 필요가 없습니다.

열거체의 정의 및 사용

자바에서는 enum 키워드를 사용하여 열거체를 정의할 수 있습니다.

enum 열거체이름 { 상수1이름, 상수2이름, ... }
enum Rainbow { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET }

사용방법

문법

열거체이름.상수이름

예제

Rainbow.RED

열거체의 상숫값 정의 및 추가

위와 같이 정의된 열거체의 첫 번째 상숫값은 0부터 설정되며, 그다음은 바로 앞의 상숫값보다 1만큼 증가되며 설정됩니다.

또한, 불규칙한 값을 상숫값으로 설정하고 싶으면 상수의 이름 옆에 괄호(())을 추가하고, 그 안에 원하는 상숫값을 명시할 수 있습니다.

하지만 이때에는 불규칙한 특정 값을 저장할 수 있는 인스턴스 변수와 생성자를 다음 예제와 같이 별도로 추가해야만 합니다.

enum Rainbow {

    RED(3), ORANGE(10), YELLOW(21), GREEN(5), BLUE(1), INDIGO(-1), VIOLET(-11);

 

    private final int value;

    Rainbow(int value) { this.value = value; }

    public int getValue() { return value; }

}

enum이 제공하는 메소드 (values()와 valueOf())


values() 메소드

values() 메소드는 해당 열거체의 모든 상수를 저장한 배열을 생성하여 반환합니다.

이 메소드는 자바의 모든 열거체에 컴파일러가 자동으로 추가해 주는 메소드입니다.

enum Rainbow { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET }

 

public class Enum01 {

    public static void main(String[] args) {

        Rainbow[] arr = Rainbow.values();

        for (Rainbow rb : arr) {

            System.out.println(rb);

        }

    }

}

valueOf() 메소드

valueOf() 메소드는 전달된 문자열과 일치하는 해당 열거체의 상수를 반환합니다.

enum Rainbow { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET }

 

public class Enum02 {

    public static void main(String[] args) {

        Rainbow rb = Rainbow.valueOf("GREEN");

        System.out.println(rb);

    }

}

실행결과

GREEN

java.lang.Enum


Enum 클래스는 모든 자바 열거체의 공통된 조상 클래스입니다.

Enum 클래스에는 열거체를 조작하기 위한 다양한 메소드가 포함되어 있습니다.

대표적인 Enum 메소드

EnumSet


EnumSet은 내부적으로 bit flag를 사용하고 있어 빠르며, 더 안전하게 다룰 수 있게 해준다.

  • EnumSet은 enum 타입에 사용하기 위한 특수한 Set 구현이다.
  • EnumSet은 내부적으로 bit vector로 표현된다. 따라서 매우 효율적이다.
  • 이 클래스를 구현할 때 공간/시간 퍼포먼스는 비트 플래그의 대안으로 사용할 수 있을 정도로 고수준이어야 한다.
import java.util.EnumSet;

import java.util.Set;

/**
 * Simple Java Program to demonstrate how to use EnumSet.
 * It has some interesting use cases and it's specialized collection for
 * Enumeration types. Using Enum with EnumSet will give you far better
 * performance than using Enum with HashSet, or LinkedHashSet.
 *
 * @author Javin Paul
 */
public class EnumSetDemo {

    private enum Color {
        RED(255, 0, 0), GREEN(0, 255, 0), BLUE(0, 0, 255);
        private int r;
        private int g;
        private int b;
        private Color(int r, int g, int b) {
            this.r = r;
            this.g = g;
            this.b = b;
        }
        public int getR() {
            return r;
        }
        public int getG() {
            return g;
        }
        public int getB() {
            return b;
        }
    }


    public static void main(String args[]) {
        // this will draw line in yellow color
        EnumSet<Color> yellow = EnumSet.of(Color.RED, Color.GREEN);
        drawLine(yellow);
        // RED + GREEN + BLUE = WHITE
        EnumSet<Color> white = EnumSet.of(Color.RED, Color.GREEN, Color.BLUE);
        drawLine(white);
        // RED + BLUE = PINK
        EnumSet<Color> pink = EnumSet.of(Color.RED, Color.BLUE);
        drawLine(pink);
    }


    public static void drawLine(Set<Color> colors) {
        System.out.println("Requested Colors to draw lines : " + colors);
        for (Color c : colors) {
            System.out.println("drawing line in color : " + c);
        }
    }
}

출력결과

Requested Colors to draw lines : [RED, GREEN]
drawing line in color : RED
drawing line in color : GREEN

Requested Colors to draw lines : [RED, GREEN, BLUE]
drawing line in color : RED
drawing line in color : GREEN
drawing line in color : BLUE

Requested Colors to draw lines : [RED, BLUE]
drawing line in color : RED
drawing line in color : BLUE

<출처>


좋은 웹페이지 즐겨찾기