Tuesday, October 09, 2007

Java String Switch

The thing I miss about Java is that it doesn't have string switch functionality like C#. The only way to get close to achieving this in Java is through enums.

A lot of people wonder how that can be done but when I read on a forum post about it I decided to do it myself.
Firstly you'll need the strings you want to look out for. Create an enum containing them, just know that it can only be 1 word strings, don't even try multiple words!

enum StrList
{
car,
dog,
human
}

Now we can take a whole string and pass it through the switch statement.

switch(StrList.valueOf(incommingStr.toLowerCase()))
{
case car:
//Do what you want with the 'car'
break;
case dog:
//Do what you want with the 'dog'
break;
case human:
//Do what you want with the 'human'
break;
}

Voila! Ok not the best way of doing it but atleast you would have string switching! ;-)
I would like to look into HashMaps to do this, since Enums perform mappings from string to the actual enum element.
Hope this was interresting or helpful to you. The only reason why you'd want to do this instead of a list of if/else if statements is performance (it is also a bit more readable).

No comments: