Strings in Switch

Reinier Zwitserloot reinier at zwitserloot.com
Sun Dec 6 19:38:02 PST 2009


Paul, I don't think there are any cases that are going to occur in real
life.

The problem is false positives. Let' say I write:

String x = getSomeString();
switch (x) {
    case "hello": doX(); break;
    case "world": doY(); break;
}

'hello' and 'world' have different hashes, so it seems we can just desugar
this to:

switch(x.hashCode()) {
   case "hello".hashCode(): doX(); break;
   case "world".hashCode(): doY(); break;
}


but that's not the right desugaring, because if I return some string that
ISNT "hello" but so happens to hashCode to the same hashCode as "hello",
then we just broke the program.

There's no way to know that x.hashCode() couldn't possibly collide, unless x
is a compile time literal. However, that seems to be a rather rare academic
case; case expressions already need to be compile time constants, so this
would mean we have a switch statement comprised of 100% compile time
literals. Something like:

switch ("hello") {
case "hello": ....
case "world": ....
}

other than debug code and some half-hearted attempt at macroing, this isn't
ever going to occur in java code. I don't think its a good idea to burden
either the JLS or javac with a special case for this scenario; the dual
switch one will handle this just fine.

Of course, if there's some other code form which could be computed without
possible collision issues in a single switch statement, please show it to us
so we can come up with a strategy for detecting this situation.

--Reinier Zwitserloot




On Sun, Dec 6, 2009 at 2:35 AM, Paul Benedict <pbenedict at apache.org> wrote:

> Joe,
>
> I reviewed the check-in and read a presentation about the
> implementation. I get that it translates into two switch statements,
> but I think there are cases where the duality can be eliminated. If
> the first switch statement produces no hash collisions, I don't think
> the second switch statement is necessary. Thoughts?
>
> Paul
>
>



More information about the coin-dev mailing list