问题描述:

I would like to do something like this:

int i = 0;

switch(difficulty) {

case 1: i++; break;

case 2: i--; break;

default: case 1;

}

Is something like this possible? I want to prevent duplicate code. I know that in this particular example there is little reason to do this, since the duplicated code would be small. The only thing I can come up with is something like this [using the fall through abilities of switch cases]:

switch(difficulty) {

case 2: i--; break;

default:

case 1: i++; break;

}

I would rather not do it like this, since it would make more sense to increase case numbers and have the default at the bottom.

But I wonder that if I would do this, would it mess up with the goto statements under the hood? In particular, will it not take longer to decide which goto statement to use since the numbers or out of order? Does the order matter in the switch statement? Imagine all cases have the same odds of being called, would it matter if you had them in random order instead of linear order?

[Edit: for my side question about efficiency I found this: Does the order matter of switch-statements, the short answer is no: Does switch case order affect speed?

How does Java's switch work under the hood?

网友答案:

This is probably what you need/want, and is valid code

int i = 0;      
    switch (difficulty) {
    default:
    case 1: i++; break;
    case 2: i--; break;
    }
网友答案:

This should suit your needs:

switch(difficulty) {
    case 2: i--; break;
    default: i++; break;
}
网友答案:

As far as I know, the order of the cases does not alter in any way the switch statement, either your parameter is fit for a case or it isn't, so it doesn't matter, in your case, which case you have first. You can see the documentation as reference if you wish. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

网友答案:

(moved from comment, since it seemed to be helpful)

Add a private method and call it from both case 1 and default, that way you won't have duplicated code.

网友答案:

No, in switch statement order doesn't matter at all. Also the compiler always maintain a hash table for jumping to the switch statement. So ordering or increase of casing is not a matter at all. It's always a O(1) operation. However, this will reduce the switching for your case:

switch(difficulty) {
    case 2: i--; break;
    default: i++; break;
}
相关阅读:
Top