Java – switch statement, which defaults to the previously defined switch case?

I want to do something like this:

int i = 0;

switch(difficulty) {
    case 1: i++; break;
    case 2: i--; break;
    default: case 1;
}

Is such a thing possible? I want to prevent duplicate code I know there is no reason to do this in this particular example because the duplicate code will be very small The only thing I can think of is [reduced ability to use the switch box]:

switch(difficulty) {
    case 2: i--; break;
    default:
    case 1: i++; break;
}

I'd rather not, because it makes more sense to increase the number of cases and have a default value at the bottom

But I wonder, if I do, will it screw up the goto statement under the hood? In particular, does it take longer to decide which goto statement to use because of numbers or out of order? Is the order important in the switch statement? Imagine that all cases have the same probability of being called. Would it make sense if you put them together in random order rather than linear order?

[editor: for my question about efficiency, I found this point: is the order of exchange statements important? The short answer is no: does switch case order affect speed? How does Java's switch work under the hood?

Solution

This may be what you need / want and is valid code

int i = 0;      
    switch (difficulty) {
    default:
    case 1: i++; break;
    case 2: i--; break;
    }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>