Java Enums and Objective-C Enums

I have the following listing in Objective-C:

typedef enum { APIErrorOne = 1, APIErrorTwo, APIErrorThree, APIErrorFour } APIErrorCode; 

I use indexes to reference an enumeration from xml, for example xml may have error = 2 , which maps to APIErrorTwo

My thread - I get an integer from xml and run the switch statement as follows:

 int errorCode = 3 switch(errorCode){ case APIErrorOne: // break; [...] } 

Java seems to dislike this kind of enumeration in the switch statement:

enter image description here

In Java, it seems like you cannot assign indexes to enum members. How can I get the Java equivalent from the above?

+4
source share
2 answers

One question per message is a general rule.

But evolution is the answer of JB Nizer.

 public enum APIErrorCode { APIErrorOne(1), APIErrorTwo(27), APIErrorThree(42), APIErrorFour(54); private final int code; private APIErrorCode(int code) { this.code = code; } public int getCode() { return this.code; } public static APIErrorCode getAPIErrorCodeByCode(int error) { if(Util.errorMap.containsKey(error)) { return Util.errorMap.get(error); } //Or create some default code throw new IllegalStateException("Error code not found, code:" + error); } //We need a inner class because enum are initialized even before static block private static class Util { private static final Map<Integer,APIErrorCode> errorMap = new HashMap<Integer,APIErrorCode>(); static { for(APIErrorCode code : APIErrorCode.values()){ errorMap.put(code.getCode(), code); } } } } 

Then in your code you can write

 int errorCode = 3 switch(APIErrorCode.getAPIErrorCodeByCode(errorCode){ case APIErrorOne: // break; [...] } 
+3
source

Java enums have a built-in ordinal , which is 0 for the first member of the enumeration, 1 for the second, etc.

But enums are classes in Java, so you can also assign them a field:

 enum APIErrorCode { APIErrorOne(1), APIErrorTwo(27), APIErrorThree(42), APIErrorFour(54); private int code; private APIErrorCode(int code) { this.code = code; } public int getCode() { return this.code; } } 
+6
source

All Articles