• Post Reply Bookmark Topic Watch Topic
  • New Topic

Map 2 enums  RSS feed

 
Vani Kumar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have 2 enums like below





How can i map the same names in 2 enums and get message from enum 1 and code from enum 2.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37510
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vani,
This feels like poor design. Why not just merge the two enums into one that has all the info you need? Or create another class that actually maps one enum (as key) to the other (as value)?

It is possible to do what you are asking, just brittle. You can convert the first enum to a String and then use that String to create the right second enum:


Also, note that it is convention to begin class/enum names with an uppercase letter.
 
Paul Murray-Cbr
Greenhorn
Posts: 12
Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vani Kumar wrote:I have 2 enums like below



Woah! name() is part of the base API for enums - it returns TEST_ENUM_1 or TEST_ENUM_2 in this case. It's a bad idea to hide or override that method by declaring anything called 'name' in the enum class.

However, in answer to your question you are probably after the static method 'valueOf' on java.lang.Enum. This will be ok if you want to use the java language name() to get from Enum1 to Enum2. If you want to use your special name feild, then you can use EnumSet to go through all the enums in enum2 and find the one you are looking for, or you can use the constructor in enum2 to build a Map.

Go look at the API docs for java.lang.Enum.name() and .valueOf(), and look at the API docs for EnumSet.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!