Java Enum return Int

前端 未结 8 2019
小鲜肉
小鲜肉 2020-12-13 03:31

I\'m having trouble declaring an enum. What I\'m trying to create is an enum for a \'DownloadType\', where there are 3 download types (AUDIO, VIDEO, AUDIO_AND_VIDEO).

<
8条回答
  •  执念已碎
    2020-12-13 04:04

    If you need to get the int value, just have a getter for the value in your ENUM:

    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
    }
    

    Or you could simple use the ordinal() method, which would return the position of the enum constant in the enum.

    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
    

提交回复
热议问题