| Oliver Wong 2006-03-09, 6:55 pm |
| [post slightly re-ordered]
"Frank Swarbrick" <Frank.Swarbrick@efirstbank.com> wrote in message
news:47972lFeicknU1@individual.net...
> Richard<riplin@Azonic.co.nz> 03/07/06 2:11 PM >>>
>
> Without something similar to COBOL's EVALUATE you must, in Java, do
> something like....
>
> if (myString == "one") {
> one();
> }
> else if (myString == "two") {
> two();
> }
> else if (myString == "three") {
> three();
> }
> else {
> four();
> }
>
> Of course the above assumes we're comparing the value of the object
> myString
> and not the object itself. I'm now totally as to which does
> what...
As Richard said, == compares references ("pointer addresses" if you want
to think of that way, though in a technical/pedantic manner, that's not
strictly correct), while .equals() invokes the "equals" method, which can be
programmed to do anything you want. In the case of Strings, "equals"
compares the contents of the strings for equality (in a case-sensitive
manner).
So in Java, you'd probably be writing:
if ("one".equals(myString)) {
one();
} else if ("two".equals(myString)) {
two();
}
/*etc.*/
>
> Wouldn't it be nicer to say:
> switch (myString) {
> case "one":
> one();
> break;
> case "two":
> two();
> break;
> case "three":
> three();
> break;
> default:
> four();
> break;
> }
In the special case of Java, I'd say "yes". The reason is that Java
already made the mistake (well, it's a mistake in my opinion) of sometimes
treating Strings like primitives, and other times treating them like
Objects. The above kind of construct perpetuates this illusion that Strings
are like primitives.
So "normally", I'd say "no", and that the above construct would detract
from the (mathematical) elegance of the language. However, since Java has
already went down the road of treating Strings like primitive, the above
construct won't add much more harm, and does provide some convenience to the
programmer, so my final answer is "Yes, that'd be nice."
>
> (Actually, eliminating those silly 'breaks' woul be even nicer, but...)
I agree. I'd like for the default behaviour to be a break, and if a
fall-through is desired, for that to be explicitly said. E.g.
switch (myInteger) {
case 1:
handleOne();
case 2:
fallthrough;
case 3:
fallthrough;
case 4:
handleTwoToFourButNotFive();
fallthrough;
case 5:
handleTwoToFive();
default:
handleDefaultCase();
}
- Oliver
|