Use an array as a case statement in switch

Todor Grudev picture Todor Grudev · Dec 18, 2013 · Viewed 89.9k times · Source

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;
}

Answer

Martijn Courteaux picture Martijn Courteaux · Dec 18, 2013

@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;
}