switch expression can't be float, double or bo

2019-01-14 10:56发布

问题:

Why doesn't the switch expression allow long, float, double or boolean values in Java? why is only int (and those that are automatoically promoted to int) allowed?

回答1:

Float and double would be awkward to use reliably even if they were possible - don't forget that performing exact equality matches on float/double is usually a bad idea anyway, due to the nature of the representation.

For Boolean values, why not just use if to start with?

I can't remember ever wanting to switch on any of these types, to be honest. Do you have a particular use case in mind?



回答2:

You can use enum in a switch statement and Java 7 will add String AFAIK. The switch statement comes from C where only int's were allowed and implementing other types is more complicated.

Floating point numbers are not a good candiates for switch as exact comparison is often broken by rounding errors. e.g. 0.11 - 0.1 == 0.01 is false.

switch on boolean is not much use as a plain if statement would be simpler

if(a) {

} else { 

}

would not be simpler with

switch(a) {
  case true:

     break;
  case false:

     break;
}

BTW: I would use switch(long) if it were available, but its not. Its a rare use case for me any way.



回答3:

Usually switch-case structure is used when executing some operations based on a state variable. There an int has more than enough options. Boolean has only two so a normal if is usually good enough. Doubles and floats aren't really that accurate to be used in this fashion.

Frankly I can't imagine a use case for this stuff, did you have some practical problem in mind with this question?



回答4:

For float and double float and double I'd assume they have omitted it for the same reasons as why it's a bad idea to compare them using ==.

For boolean, it may simply be because it would correspond to an if statement anyway. Remember that you can only have constants in the case-expressions, so the cases would always correspond to if (someBool) and if (!someBool).

For long I don't have an explanation. Seems to me that such feature perhaps should have been included when designing the language.