I had a little problem with casting Java long type to Enum type and can't find a solution how to do that.
Here is what I'm using :
public enum DataType {
    IMAGES(1),
    VIDEOS(2);
    private int value;
    private DataType(int i){
        this.value = i;
    }
}
and I need to do something like this:
DataType dataType;
String thiz = "1";
long numb = Long.parseLong(thiz);
dataType = numb;
The error that I get says:
Convert numb to DataType or convert dataType to long.
Second Scenario:
I have this :
static String[] packetType;
String tmp=incomingData.toString(); // where incomingData is byte[]
int lastLoc = 0;
int needsSize = packetFieldSizes[tmpCurrentField-1]; // where packetFieldSizes,tmpCurrentField are integers.
thiz=tmp.substring(lastLoc, needsSize);    
packetType=thiz;  // packetType = thiz copy; where thiz is the same as used above.
I tried to convert thiz to String[] and use valueOf,but
Any suggestions how to get the thinks to work?
Thanks in advance!
Enum already provides a unique integer for each of it's instances. Check out ordinal(). (Note that it's zero-based though.)
If you need to go from a long to a DataType you can do
DataType dataType;
String thiz;
long numb = Long.parseLong(thiz);
dataType = DataType.values()[(int) numb];
A complete list of conversions from and to enum constants, strings and integers can be found in this answer:
If for some reason you need to assign the numbers yourself and thereby can't use aioobe's good solution, you can do something like the following:
public enum DataType {
    IMAGES(1),
    VIDEOS(2);
 private final int value;
 private DataType(int i){
    this.value=i;
 }
 public static DataType getByValue(int i) {
     for(DataType dt : DataType.values()) {
         if(dt.value == i) {
             return dt;
         }
     }
     throw new IllegalArgumentException("no datatype with " + i + " exists");
 }
The static method getByValue() searches for the DataType with the provided number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With