First, you should NOT compare strings using ==
. It is nearly always a bug. For example:
if ("hello" == new String("hello")) {
System.out.println("Something impossible just happened!!");
}
(The only cases where it is not a bug involve comparison of String literals and/or manually "interned" String objects. And even then, it is a rather dubious optimization because its correctness depends on you never using "normal" strings.)
In Java 6 and earlier there is no way do a sequence of String equals
comparisons that is BOTH more concise than AND as efficient as the original version.
Using Arrays.asList
, as in
if (Arrays.asList("bar-owner", "barrista",
"shop owner").contains(characterStrings[occupation])) {
// statements
}
is more concise, but it is also significantly less efficient:
The contains
call must internally iterate over the elements of the list object, testing each one with equals
.
The asList
call involves allocating and initializing the String[]
for the varargs argument, and allocating and initializing the List
object returned by the call. (You can potentially "hoist" this to improve performance, but that detracts from the conciseness ...)
In Java 7:
switch (characterStrings[occupation]) {
case "bar-owner": case "barrista": case "shop owner":
// statements
break;
}
is more concise, and could also be more efficient. It is plausible that the Java compiler(s) could turn that into a lookup in a hidden static HashSet<String>
or the equivalent. There is going to be a "break even" point where cost of a sequence of N equals
tests is greater than the cost of a hash table lookup.