Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer value to matching Java Enum

Tags:

java

I've an enum like this:

public enum PcapLinkType {   DLT_NULL(0)   DLT_EN10MB(1)   DLT_EN3MB(2),   DLT_AX25(3),   /*snip, 200 more enums, not always consecutive.*/   DLT_UNKNOWN(-1);     private final int value;         PcapLinkType(int value) {         this.value= value;     } } 

Now I get an int from external input and want the matching input - throwing an exception if a value does not exist is ok, but preferably I'd have it be DLT_UNKNOWN in that case.

int val = in.readInt(); PcapLinkType type = ???; /*convert val to a PcapLinkType */ 
like image 229
Lyke Avatar asked Mar 13 '11 22:03

Lyke


People also ask

Can we use integer in enum?

No, we can have only strings as elements in an enumeration.

Can you use == for enums Java?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

Can you assign a value to an enum in Java?

By default enums have their own string values, we can also assign some custom values to enums.


1 Answers

You would need to do this manually, by adding a a static map in the class that maps Integers to enums, such as

private static final Map<Integer, PcapLinkType> intToTypeMap = new HashMap<Integer, PcapLinkType>(); static {     for (PcapLinkType type : PcapLinkType.values()) {         intToTypeMap.put(type.value, type);     } }  public static PcapLinkType fromInt(int i) {     PcapLinkType type = intToTypeMap.get(Integer.valueOf(i));     if (type == null)          return PcapLinkType.DLT_UNKNOWN;     return type; } 
like image 134
MeBigFatGuy Avatar answered Nov 15 '22 13:11

MeBigFatGuy