I am trying to do something like this, i.e., use an array in a switch statement. Is it possible in Java? If it isn't, please explain a possible solution.
boolean[] values = new boolean[4]; values[0] = true; values[1] = false; values[2] = false; values[3] = true; switch (values) { case [true, false, true, false]: break; case [false, false, true, false]: break; default: break; }
Yes, you can pass an array to a switch.
In C, you cannot use arrays in switch (and expressions for case ). Also, the type passed to switch() and types specified in each case must match. So the most you can do is switch on a character.
The switch statement evaluates the integer expression in parentheses and compares its value to all cases. Each case must be labeled by an integer or character constant or constant expression. Each label must be unique. So, you can't switch on the userNumbers array.
Explanation: The switch/case statement in the c language is defined by the language specification to use an int value, so you can not use a float value. The value of the 'expression' in a switch-case statement must be an integer, char, short, long. Float and double are not allowed.
@sᴜʀᴇsʜ ᴀᴛᴛᴀ is right. But I wanted to add something. Since Java 7, switch statements support Strings, so you could do something with that. It is really dirty and I do not recommend, but this works:
boolean[] values = new boolean[4]; values[0] = true; values[1] = false; values[2] = false; values[3] = true; switch (Arrays.toString(values)) { case "[true, false, true, false]": break; case "[false, false, true, false]": break; default: break; }
For those concerned about performance: you are right, this is not super fast. This will be compiled into something like this:
String temp = Arrays.toString(values) int hash = temp.hashCode(); switch (hash) { case 0x23fe8da: // Assume this is the hashCode for that // original string, computed at compile-time if (temp.equals("[true, false, true, false]")) { } break; case 0x281ddaa: if (temp.equals("[false, false, true, false]")) { } break; default: break; }
NO, simply you cannot.
SwitchStatement: switch ( Expression ) SwitchBlock
The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With