Thursday, September 30, 2010

No more equals...just switch

Just remove one restriction from your mind that only the legal argument type of a switch statement is int, or any other type that can be promoted to int: byte, short, or char.
Now with the jdk1.7 it can be a String also......a big overhead of using equals have been solved by sun....

OverHead with equals::
String cmd="your string";
if(cmd.equals("dir"))
showDir();
else if(cmd.equals("cls"))
clearScreen();
else if(cmd.equals("exit"))
exitFrom();
else
goToHell();

a big overhead of if/else ladder and all,
a lenghty code,
but now leave the clumpsy else-if ladder
just switch to "switch"

String cmd="your string";
switch(cmd)
{
case "dir":
showDir();
break;
case "cls":
clearScreen();
break;
case "exit":
exitFrom();
break;
default: //the beauty of switch
goToHell();
}

0 comments:

Post a Comment