New in Java 7: switch()ing on Strings

Finally, Java can switch on Strings! No more inefficient strings of if/else chains or Hash lookups or translation into Enums. Finally just clean readable and intuitive code.

switch(suit) {
  case "club":
  case "diamond":
    trickValue = 20;
    break;
  case "heart":
  case "spade":
    trickValue = 30;
    break;
  case "no-trump":
    trickValue = 40;
    break;
}

It’s actually just syntactic sugar. The java compiler renders this all down to int switching by pre-computing the .hashcode() of all of the labels since they have to be constants anyway (unlike languages like PHP where you can do some really neat shenanigans). Because this still renders down to primitives, Java still gets the jump table optimizations that were the whole motivation of the switch construct in the first place.

If you use Eclipse, switching on a String will still probably give you an error. It wasn’t until September 2011’s release (3.7.1) that this was implemented. There were versions of Indigo that didn’t support this, so you’ll need the latest one.

One Comment

Post a Comment

Your email is kept private. Required fields are marked *