简体   繁体   中英

Multiple values in switch case / converting ifs to switch statement

I have a big list of Ifs, and I want to change it into a switch statement. Currently it looks like this:

if(x == 1){
    ...
}
if(x == 2){
    ...
}
if(myArray.contains(x)){
    ...
}

In actuality it's a bit longer than this, but it's the third if in the example that confuses me - how do I change that around to get it to work in a switch, or is it even possible?

You could do something like this, but YMMV according to possible exit conditions in your code:

switch (x) {
case 1: 
  ...
  break;
case 2:
  ...
  break;
case 3:
case 4:
  ... multi-case
  break;
default:
  if(myArray.contains(x)){
    ...
  }
}

Switch statement can be used only to test equality of x

So if not equality conditions like ( if(myArray.contains(x)) ) must come at the end, then you can copy paste this into default section of switch

It would look this way

    switch (x) {
     case 1:   ...; break;
     case 2:   ...; break;
     default: if(myArray.contains(x)) ...
    }

If not equality conditions would need to be in the middle, then its not possible to use switch.

reference: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

You can only swith over the x value. That means the last condition will not be part of the switch:

switch(x) {
case 1:
    ...
    break;
case 2:
    ...
    break;
}
if(myArray.contains(x)){
    ...
}

Yes, it is possible. The switch statement will make it a little cleaner and easier to maintain. You have to worry about x because it has to be compile-time constant.

switch(x) {
 case 1:
    doSomething();
    break();
 case 2:
    doSomethingElse();
    break();

default:
 if(myArray.contains(x)){

 }


//etc...
}

This doesn't look very Object Oriented.

Try to refactor your code with "Replace conditional with polymorphism" http://martinfowler.com/refactoring/catalog/replaceConditionalWithPolymorphism.html

A map can help you to do some lookups, if you need to convert from int to custom object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM