Nick Cameo
Nick Cameo

Reputation: 419

Non ordinal INT as Enum

Please consider the following java enum:

public enum carrier {
    Default(0),
    CarrierOne(1),
    CarrierTwo(2),
    CarrierWhoKnows(102312);
    private final int value;
    private static final Map<Integer, carrier> carrierMap = new HashMap<Integer, carrier>();

    static {
        for (carrier type : carrier.values()) {
            carrierMap.put(type.value, type);
        }
    }

    private carrier(int value) {
        this.value = value;
    }

    public static int getIntValue(int value) {
        return value;
    }

    public static carrier getStringValue(int value) {
        return carrierMap.get(value);
    }
}   

What I need is for getIntValue to return the value as it does (ie, 102312) however, as an enum and not an int. Is it possible to cast the int value 102312 as an enum. Please note, I am not referring to the ordinal (we don't use that), or the string value which is correctly returned in getStringValue. I am referring to returning the value 102312 as an enum instead of int.

Thanks in Advance,

Nick.

Upvotes: 0

Views: 104

Answers (1)

hatesms
hatesms

Reputation: 760

If I understand you well, you just want to get enum member by it int value.

public static carrier getStringValue(int value) {
    for(carrier c : carrier .values()){
        if(c.value == value) return c;
    }
    throw new IllegalArgumentException("Got illegal value");
}

Please check you code to be more readable. Change method names, rename enum name(must be Carrier), think about getIntValue method signature and implemetnation. Looks like it should be opposite to getStringValue and return int value of enum member

public static int getIntValue(carrier c) {
   if(c == null) throw new IllegalArgumentException("Got null, expected carrier");     
   return c.value;
}

Upvotes: 1

Related Questions