Is it possible to assign numeric value to an enum in Java?

后端 未结 6 996
傲寒
傲寒 2020-12-07 17:29

Is anything like this possible in Java? Can one assign custom numeric values to enum elements in Java?

public enum EXIT_CODE {
    A=104, B=203;
}

6条回答
  •  温柔的废话
    2020-12-07 17:53

    Extending Bhesh Gurung's answer for assigning values, you can add explicit method to set value

       public ExitCode setValue( int value){
          //  A(104), B(203);
          switch(value){
            case 104: return ExitCode.A;
            case 203: return ExitCode.B;
            default:
                       return ExitCode.Unknown //Keep an default or error enum handy
          }
       }
    

    From calling application

    int i = 104; 
    ExitCode serverExitCode = ExitCode.setValue(i);
    

    //You've valid enum from now

    [Unable to comment to his answer, hence posting it separately]

提交回复
热议问题