Link to home
Start Free TrialLog in
Avatar of DaFou
DaFou

asked on

switch with a string

Ola,

I want to do something like a switch but then for usage with strings.
as I understand switch is used switch ( int )

But how do i emulate switch ( String )

I am thinking of something like this
switch ( FunctionThatTransformsStringToInt( SomeStringVariable ) )
{
  case FunctionThatTransformsStringToInt( "SomeSting" ) :
}

how to make something like this work or what other ways are there?
Avatar of petmagdy
petmagdy
Flag of Canada image

the problem is "case" token only takes constant expersion, but u can do something like that:

public class SwitchString {
   
    public static void main(String[] args) {
        String color = "white";
       
        switch(color.hashCode())
        {
         case 12:
             System.out.println("Yellow!!");
         
        }
    }
}

assuming u know the hashCode values already
ASKER CERTIFIED SOLUTION
Avatar of petmagdy
petmagdy
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
also what is wrong with?:

if("while".equals(color) )
{

}
else if("yellow".equals(color) )
{

}
.....
Avatar of DaFou
DaFou

ASKER

with more then 2 options anything other then a switch will result in performance loss
also using a switch statment one can group situation like

switch ( int )
{
  case 1 :
  case 2 :
    // do something
    break;
  case 3 :
  // do something else
}

and the switch simply looks much better then else if