In the above program, I am using enum for the operating system. The switch case needs to be performed based upon the user input. The return type of readLine() is string. How can we change the String to enum.
Hentay Duke
Ranch Hand
Joined: Oct 27, 2004
Posts: 198
posted
0
Please ignore this post as I have no idea what I'm talking about!
Many problems here;
1.) you need to read about enumeration as you're not using it properly. It cycles though a collection one element at a time.
this statement
makes no sense(unless it's something in 5.0 that I don't know) it should be something like this (psuedo code off the top of my head)
That's an excellent question, Sachin, and it's one that will be raised frequently going forward.
Individual enums tend to be short (dozens not hundreds) and the enum has a set of very useful helper methods. The name attribute string-izes the value of the enuemrations, for example.
for( Color color : Color.values() ) { if( color.name().equals("Blue") ) ... do something ... }
If you use it a great deal it would make sense to create a map of string values and enum values. Declare a Map<String, Color> and populate as follows:
for( Color color : Color.values() ) { map.put(color.name(), color); } [ September 20, 2005: Message edited by: Rick O'Shay ]
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
posted
0
[Rick]: If you use it a great deal it would make sense to create a map of string values and enum values.
For what? Seems to me that we get everything we need from the valueOf(), name(), and values() methods already built into enums:
I'm not sure what else we'd need... [ September 20, 2005: Message edited by: Jim Yingst ]
"I'm not back." - Bill Harding, Twister
Hentay Duke
Ranch Hand
Joined: Oct 27, 2004
Posts: 198
posted
0
So sorry, maybe I'll just be quiet until I get up to speed with 5.0.
Tony Morris
Ranch Hand
Joined: Sep 24, 2003
Posts: 1608
posted
0
There is a mapping from the enum field name to the enum instance itself implicitly using the valueOf method. Quite often, you need to use something other than the field name as the key, in which case, the API Specification recommends the use of EnumMap. Being the person I am, I recognise that this approach is somewhat flawed, so I suggest using a Map, perhaps lazily loaded (within a static nested class of the enum type). At least, this is what I do.
That is true, you do have everything you need with the possible exception, npi, that Color.valueOf("seafoam") would throw an IllegalArgumentException should somebody have the audacity to create a Color enumeration without it. With a map you don't get shot just for asking. Then again you have to pack that map with you so the built-in is far better on balance.