Programing

Java에서 enum의 서수를 지정할 수 있습니까?

lottogame 2020. 11. 14. 09:45
반응형

Java에서 enum의 서수를 지정할 수 있습니까?


ordinal()메서드는 열거 형 인스턴스의 서수를 반환합니다.
열거 형의 서수를 어떻게 설정할 수 있습니까?


설정할 수 없습니다. 항상 상수 정의의 서수입니다. Enum.ordinal ()에 대한 설명서를 참조하십시오 .

이 열거 형 상수의 서수 (초기 상수에 0의 서 수가 할당 된 열거 형 선언의 위치)를 반환합니다. 대부분의 프로그래머는이 방법을 사용하지 않습니다. EnumSet 및 EnumMap과 같은 정교한 열거 기반 데이터 구조에서 사용하도록 설계되었습니다.

그리고 실제로-당신은 그럴 필요가 없습니다. 정수 속성을 원하면 하나를 정의하십시오.


열거 형의 순서를 변경하여 서수를 제어 할 수 있지만 에서처럼 명시 적으로 설정할 수는 없습니다 C++. 한 가지 해결 방법은 원하는 번호에 대한 열거 형에 추가 메서드를 제공하는 것입니다.

enum Foo {
  BAR(3),
  BAZ(5);
  private final int val;
  private Foo(int v) { val = v; }
  public int getVal() { return val; }
}

이 상황 BAR.ordinal() == 0에서는 BAR.getVal() == 3.


리플렉션을 사용하여 서수를 업데이트 할 수 있습니다.

private void setEnumOrdinal(Enum object, int ordinal) {
    Field field;
    try {
        field = object.getClass().getSuperclass().getDeclaredField("ordinal");
        field.setAccessible(true);
        field.set(object, ordinal);
    } catch (Exception ex) {
        throw new RuntimeException("Can't update enum ordinal: " + ex);
    }
}

수락 된 답변이 지적했듯이 서수를 설정할 수 없습니다. 이에 가장 가까운 것은 사용자 정의 속성을 사용하는 것입니다 .

public enum MonthEnum {

    JANUARY(1),
    FEBRUARY(2),
    MARCH(3),
    APRIL(4),
    MAY(5),
    JUNE(6),
    JULY(7),
    AUGUST(8),
    SEPTEMBER(9),
    OCTOBER(10),
    NOVEMBER(11),
    DECEMBER(12);

    MonthEnum(int monthOfYear) {
        this.monthOfYear = monthOfYear;
    }

    private int monthOfYear;

    public int asMonthOfYear() {
        return monthOfYear;
    }

}

참고 : 기본적으로 enum값을 지정하지 않으면 값 0(아님 1) 에서 시작 합니다. 또한 값은 1각 항목에 대해 증가 할 필요가 없습니다 .


에서 http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Enum.html

public final int ordinal()Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap.

Returns: the ordinal of this enumeration constant

If you have

public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

then SUNDAY has an ordinal of 0, MONDAY is 1, and so on...


Check out the Java Enum examples and docs

Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap.


The easy answer: just change the order of the constants. The first defined will be 0, the second will be 1, etc. However, this may not be practical if you have constantly changing code, or enums will many many values. You can define a custom method to work around the default ordinal, but MAKE SURE it is well documented to avoid confusion!

public enum Values
{
    ONE, TWO, THREE, FOUR;

    public int getCustomOrdinal()
    {
        if(this == ONE)
        {
            return 3;
        }
        else if(this == TWO)
        {
            return 0;
        }
        ...
    }
}

참고URL : https://stackoverflow.com/questions/5372855/can-i-specify-ordinal-for-enum-in-java

반응형