1

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.

2
  • Why are you using this construct? There are a number of cleaner ways organize the code, most notably with Map<String, MyEnum>. Commented Sep 25, 2013 at 14:41
  • @chrylis That would require major refactoring and affect many other things. Commented Sep 25, 2013 at 14:43

5 Answers 5

2

You also could use

String.valueOf()

myHashMap.put("foo", String.valueOf(MyEnum.BAR.ordinal()));
Sign up to request clarification or add additional context in comments.

Comments

1

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);

2 Comments

@chrylis You are right, but I thought that might be too much of a change. ;)
I honestly couldn't think of any situation where it makes sense that you'd want to store a String representation and store the ordinal simultaneously... something smells with the whole API, and this is the point where I put on my refactoring boots!
1

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

Comments

1

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

2 Comments

Or even myHashMap.put("foo", ""+ MyEnum.BAR.ordinal());
Or even easier: myHashMap.put("foo", Integer.toString(MyEnum.BAR.ordinal()));. @OldCurmudgeon it is not a good practice convert something to String using "" + concatenation, the fact that works doesn't mean is good.
0

I guess it is better to use enum name as key

MyEnum.BAR.name()

and conversion back

MyEnum.valueOf("BAR")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.