Use an array as a case statement in switch Use an array as a case statement in switch arrays arrays

Use an array as a case statement in switch


@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


You can't switch on whole arrays. But you could convert to a bit set at the expense of some readability of the switch itself:

switch (values[0] + 2 * values[1] + 4 * values[2] + 8 * values[3])

and use binary literals in your case statements: case 0b0101 is your first one.