Reputation: 4691
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?
Upvotes: 2
Views: 18326
Reputation: 31
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
Upvotes: 3
Reputation: 38132
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.
Upvotes: 0
Reputation: 4324
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...
}
Upvotes: 1
Reputation: 8468
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)){
...
}
}
Upvotes: 17
Reputation: 5539
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)){
...
}
Upvotes: 1