Question

I need to pass the ordinal value of an enum as a parameter to a HashMap<String, String>. In other words, I want to cast an ordinal as a String.

Right now, I'm doing this:

HashMap<String, String> myHashMap = new HashMap<String, String>();
myHashMap.put("foo", String.format("%s", MyEnum.BAR.ordinal()));

Is that the best way? The .toString() method isn't available here, and (String)MyEnum.BAR.ordinal() doesn't work.

Was it helpful?

Solution

You also could use

String.valueOf()

myHashMap.put("foo", String.valueOf(MyEnum.BAR.ordinal()));

OTHER TIPS

The ordinal() is an internal number which could change. I suggest you just use

Map<String, String> myMap = new HashMap<>();
myMap.put("foo", MyEnum.BAR.toString());

or

Map<String, Object> myMap = new HashMap<>();
myMap.put("foo", MyEnum.BAR);

or

Map<String, MyEnum> myMap = new HashMap<>();
myMap.put("foo", MyEnum.BAR);

The best way if you used HashMap<String, Integer> and did not convert ordinal to String

You could use

myHashMap.put("foo", String.format("%d", Integer.toString(MyEnum.BAR.ordinal())));

or simply (credit @OldCurmudgeon)

myHashMap.put("foo", Integer.toString(MyEnum.BAR.ordinal()));

Disclaimer: Would have to agree with comments that using Map<String, MyEnum> is a better approach

I guess it is better to use enum name as key

MyEnum.BAR.name()

and conversion back

MyEnum.valueOf("BAR")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top