IT박스

Java Enum 반환 Int

itboxs 2020. 11. 13. 07:56
반응형

Java Enum 반환 Int


열거 형을 선언하는 데 문제가 있습니다. 내가 만들려고하는 것은 3 가지 다운로드 유형 (AUDIO, VIDEO, AUDIO_AND_VIDEO)이있는 'DownloadType'에 대한 열거 형입니다.

다음과 같이 코드를 구현했습니다.

private enum DownloadType {
    AUDIO(0), VIDEO(1), AUDIO_AND_VIDEO(2);
    private final int value;

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

다음과 같이 사용하면 잘 작동합니다.

DownloadType.AUDIO_AND_VIDEO.value;

하지만 '가치'를 물을 필요가 없도록하고 싶습니다. 내가 착각 할 수도 있지만 이것은 글꼴과 같은 Java에서 여러 클래스가 작동하는 방식입니다. 예를 들어 글꼴 스타일을 설정하려면 다음을 사용합니다.

Font.PLAIN

int 값을 반환하는 경우 다음을 사용하지 않습니다.

Font.PLAIN.value

Font.PLAIN열거 형 아닙니다 . 그것은 단지 int. 열거 형에서 값을 .value가져와야 하는 경우 열거 형은 실제로 기본 형식이 아닌 자체 유형의 개체이므로 메서드를 호출하거나를 사용하는 것을 피할 수 없습니다 .

당신이 진정으로 만 필요한 경우 int, 그리고 당신의 API에 유효하지 않은 값을 전달할 수있는 사용자를 손실 유형 안전을 받아들이는 이미, 당신은 할 수 있습니다 로 그 상수 정의 int도를 :

public final class DownloadType {
    public static final int AUDIO = 0;
    public static final int VIDEO = 1;
    public static final int AUDIO_AND_VIDEO = 2;

    // If you have only static members and want to simulate a static
    // class in Java, then you can make the constructor private.
    private DownloadType() {}
}

그건 그렇고, 메서드 value도 있기 때문에 필드는 실제로 중복되므로 .ordinal()다음과 enum같이 정의 할 수 있습니다.

enum DownloadType { AUDIO, VIDEO, AUDIO_AND_VIDEO }

사용하여 "값"을 가져옵니다.

DownloadType.AUDIO_AND_VIDEO.ordinal()

편집 : 코드 수정 .. static class자바에서는 허용되지 않습니다. Java에서 정적 클래스를 정의하는 방법에 대한 설명과 세부 정보와 함께이 SO 답변참조하십시오 .


int 값을 얻으려면 ENUM의 값에 대한 getter를 사용하십시오.

private enum DownloadType {
    AUDIO(1), VIDEO(2), AUDIO_AND_VIDEO(3);
    private final int value;

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

    public int getValue() {
        return value;
    }
}

public static void main(String[] args) {
    System.out.println(DownloadType.AUDIO.getValue());           //returns 1
    System.out.println(DownloadType.VIDEO.getValue());           //returns 2
    System.out.println(DownloadType.AUDIO_AND_VIDEO.getValue()); //returns 3
}

또는 ordinal()열거 형 상수의 위치를 ​​반환 하는 메서드를 간단하게 사용할 수 있습니다 .

private enum DownloadType {
    AUDIO(0), VIDEO(1), AUDIO_AND_VIDEO(2);
    //rest of the code
}

System.out.println(DownloadType.AUDIO.ordinal());            //returns 0
System.out.println(DownloadType.VIDEO.ordinal());            //returns 1
System.out.println(DownloadType.AUDIO_AND_VIDEO.ordinal()); //returns 2

먼저 다음과 같은 질문을 해야합니다. 정말 int가 필요합니까?

열거 형의 목적은 외부 값 (예 : int)에 의존하지 않고 코드에서 의미를 갖는 항목 모음 (상수)을 갖는 것입니다. Java의 열거 형은 스위치 문에 대한 인수로 사용할 수 있으며 "=="같음 연산자 (특히)를 사용하여 안전하게 비교할 수 있습니다.

제안 1 (정수 필요 없음) :

종종 뒤에 정수가 필요하지 않은 경우 다음을 사용하십시오.

private enum DownloadType{
    AUDIO, VIDEO, AUDIO_AND_VIDEO
}

용법:

DownloadType downloadType = MyObj.getDownloadType();
if (downloadType == DownloadType.AUDIO) {
    //...
}
//or
switch (downloadType) {
  case AUDIO:  //...
          break;
  case VIDEO: //...
          break;
  case AUDIO_AND_VIDEO: //...
          break;
}

제안 2 (필요한 정수) :

그럼에도 불구하고 때로는 enum을 int로 변환하는 것이 유용 할 수 있습니다 (예 : 외부 API가 int 값을 예상하는 경우). 이 경우 toXxx()-Style을 사용하여 메서드를 변환 메서드로 표시하는 것이 좋습니다. 인쇄 무시 용 toString().

private enum DownloadType {
    AUDIO(2), VIDEO(5), AUDIO_AND_VIDEO(11);
    private final int code;

    private DownloadType(int code) {
        this.code = code;
    }

    public int toInt() {
        return code;
    }

    public String toString() {
        //only override toString, if the returned value has a meaning for the
        //human viewing this value 
        return String.valueOf(code);
    }
}

System.out.println(DownloadType.AUDIO.toInt());           //returns 2
System.out.println(DownloadType.AUDIO);                   //returns 2 via `toString/code`
System.out.println(DownloadType.AUDIO.ordinal());         //returns 0
System.out.println(DownloadType.AUDIO.name());            //returns AUDIO
System.out.println(DownloadType.VIDEO.toInt());           //returns 5
System.out.println(DownloadType.VIDEO.ordinal());         //returns 1
System.out.println(DownloadType.AUDIO_AND_VIDEO.toInt()); //returns 11

요약

  • Don't use an Integer together with an enum if you don't have to.
  • Don't rely on using ordinal() for getting an integer of an enum, because this value may change, if you change the order (for example by inserting a value). If you are considering to use ordinal() it might be better to use proposal 1.
  • Normally don't use int constants instead of enums (like in the accepted answer), because you will loose type-safety.

Simply call the ordinal() method on an enum value, to retrieve its corresponding number. There's no need to declare an addition attribute with its value, each enumerated value gets its own number by default, assigned starting from zero, incrementing by one for each value in the same order they were declared.

You shouldn't depend on the int value of an enum, only on its actual value. Enums in Java are a different kind of monster and are not like enums in C, where you depend on their integer code.

Regarding the example you provided in the question, Font.PLAIN works because that's just an integer constant of the Font class. If you absolutely need a (possibly changing) numeric code, then an enum is not the right tool for the job, better stick to numeric constants.


You can try this code .

private enum DownloadType {
    AUDIO , VIDEO , AUDIO_AND_VIDEO ;

}

You can use this enumeration as like this : DownloadType.AUDIO.ordinal(). Hope this code snippet will help you .


If you are concatenating the enum with a string you can override toString method to return the int:

public String toString() {
    return value + "";
}

Then you could simply use:

String something = "foo" + DownloadType.AUDIO;

and the toString() method will be invoked.


Note that using toString() programmatically is generally considered poor practice - it is intended for human eyes only, however this is the only way to achieve what you're asking.


Do you want to this code?

public static enum FieldIndex {
    HDB_TRX_ID,     //TRX ID
    HDB_SYS_ID      //SYSTEM ID
}

public String print(ArrayList<String> itemName){
    return itemName.get(FieldIndex.HDB_TRX_ID.ordinal());
}

참고URL : https://stackoverflow.com/questions/13792110/java-enum-return-int

반응형