Have you wondered: Why does Java hate us so much? Why do they not allow us to do a switch statement on a String?

Well maybe this little "workaround" can help you in your tasks.

In 1.5, Java introduced a new type called Enum. With this type you can "simulate" a switch as if it were on Strings.

public enum MyEnum {
 SUNNY,
 RAINY,
}

Once you have this, you can simply do a switch.

switch(MyEnum.valueOf(myString)) {
 case SUNNY: // The Weather is good
   break;
 case RAINY: // The Weather sucks
   break;
 default: // No Weather Info
   break;
}
 

So here you go.

Cheers,

3 comments

Comment from: Wookai [Visitor] · http://20-100.ch/blog
"Why does Java hate us so much?"

Lol, I feel you a bit frustrated, aren't you ;) ? I never had such a thought...

Anyway, nice workaround !

But I don't see why you would need to do a switch on Strings ? There should always be a way to do it differently, which could even be better...
03/06/08 @ 10:21
Comment from: Trefex [Member]
The why I can't share with you ^^
03/06/08 @ 11:32
This is great info to know.
10/29/08 @ 18:28

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)