0

I have the following enum:

 public static enum OpCode { a((byte) 0x0), b((byte)0x18), c((byte)0x1A); private byte value; private OpCode (byte value) { this.value = value; } byte getValue() { return value; } 

if I have the value x = 0x18 how can I get the string 'b'?

this is what I tried:

 System.out.println(OpCode.values()[x]); 

but it doesn't work

1
  • 1
    Linear search, perhaps? Commented Oct 22, 2017 at 9:59

3 Answers 3

6

You can implement static method such as fromByte :

public enum OpCode { ... truncated public static OpCode fromByte(byte x) { for(OpCode oc : values()) { if (oc.getValue() == x) { return oc; } } throw new IllegalArgumentException("Unknown OpCode value: " + x); } } 

And then you can call it like this:

OpCode oc = OpCode.fromByte(x); 
Sign up to request clarification or add additional context in comments.

Comments

4

Either linear search as Joe C suggest in its comment or use a Map to store OpCode instances by Byte value.

 public static enum OpCode { a((byte) 0x0), b((byte)0x18), c((byte)0x1A); private final byte value; private final static Map<Byte, OpCode> opCodesByByte; static { opCodesByByte = new HashMap<>(); for (OpCode opCode : values()) { opCodesByByte.put(opCode.value, opCode); } } ... } 

And also add a static method in OpCode to provide the search method :

public static OpCode of(byte value){ return opCodesByByte.get(value); } 

Note that in this implementation, it returns null if no matching.

3 Comments

I would make the map final +1
And you are right. Thanks. By the way, the value member should also be. I updated.
@davidxxx I have a question related to design of enum. Wanted to see if you can help me out.
0

You need to loop the enum:

 byte x = 0x18; for (OpCode opCode : OpCode.values()) { if (x == opCode.getValue()) { System.out.println(opCode); } } 

Alternatively, build a map like this:

 private static Map<Byte, OpCode> valueToOpCode = new HashMap<>(); static OpCode getOpCode(byte value) { return valueToOpCode.get(value); } public static enum OpCode { a((byte) 0x0), b((byte)0x18), c((byte)0x1A); private byte value; private OpCode(byte value) { this.value = value; valueToOpCode.put(value, this); } byte getValue() { return value; } } private void test() { byte x = 0x18; System.out.println(getOpCode(x)); // prints 'b' } 

1 Comment

You have to be very careful with the order of class initialization to get this to work. ideone.com/4N5pMA

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.