2013-10-15 3 views
0

에 따라 열거의 이름을 가져옵니다 I이 값이 예를 1 알려져있는 경우

public enum AppointmentSlotStatusType { 

    INACTIVE(0), ACTIVE(1); 

    private int value; 

    private AppointmentSlotStatusType(int value) { 
     this.value = value; 
    } 

    public int getValue() { 
     return value; 
    } 

    public String getName() { 
     return name(); 
    } 
} 

이 어떻게 열거 이름을 얻는 다음 열거?

+0

는'valueOf' 스타일의 메소드를 구현 쉽습니다. –

답변

6

이 특정 열거 형의 경우는

String name = TimeUnit.values()[1].name(); 
+0

'ordinal' 필드가 이미 있으므로'number' 필드는 쓸모가 없다고 덧붙일 것입니다. –

+0

@BoristheSpider 여러 가지 이유로'서수 '를 사용하는 것은 나쁜 생각입니다. –

0

Map은 정수 키의 이름을 유지 관리 할 수 ​​있습니다.

public enum AppointmentSlotStatusType { 
    INACTIVE(0), ACTIVE(1); 

    private int value; 

    private static Map<Integer, AppointmentSlotStatusType> map = new HashMap<Integer, AppointmentSlotStatusType>(); 

    static { 
     for (AppointmentSlotStatusType item : AppointmentSlotStatusType.values()) { 
      map.put(item.value, item); 
     } 
    } 

    private AppointmentSlotStatusType(final int value) { this.value = value; } 

    public static AppointmentSlotStatusType valueOf(int value) { 
     return map.get(value); 
    } 
} 

answer을 살펴보십시오.

public static AppointmentSlotStatusType forId(int id) { 
    for (AppointmentSlotStatusType type: values()) { 
     if (type.value == id) { 
      return value; 
     } 
    } 
    return null; 
} 

은 아마 당신은 또한 필드에 values()에 의해 반환 된 배열을 캐시 싶습니다 :

+4

복제본으로 이것을 닫는 이유는 무엇입니까? 이 질문과 귀하가 연결된 질문의 차이점은 어디에서 볼 수 있습니까? –

1

당신은 해당 ID 당신에게 열거 인스턴스를 줄 것이다 enum 내부 public static 방법을 구현할 수

public static final AppointmentSlotStatusType[] VALUES = values(); 

values() 대신 VALUES을 사용하십시오.


또는 Map을 대신 사용할 수 있습니다.

private static final Map<Integer, AppointmentSlotStatusType> map = new HashMap<>(); 

static { 
    for (AppointmentSlotStatusType type: values()) { 
     map.put(type.value, type); 
    } 
} 

public static AppointmentSlotStatusType forId(int id) { 
    return map.get(id); 
} 
+0

당신의 의견으로는, 메소드가 실제로'null'을 리턴하거나'Exception'을 던져 주어야할까요? –

+0

당신이 캐시하려고한다면'Map'을 사용하십시오 - O (n) 대신 O (1)입니다 ... –

+0

@SotiriosDelimanolis 여기에'null'을 반환하는 데 아무런 문제가 없다고 생각합니다. –