Re: switch using strings
On 2/20/2011 4:24 PM, Dirk Bruere at NeoPax wrote:
...which obviously won't work.
I have a series of packets coming in with a header that contains a
message name in text. I need to find a neat way to do a kind of switch
statement on the message name. Any ideas?
What's your "neatness" criterion? Several possibilities occur
to me; whether they're "neat" or "messy" is for you to decide:
1) Pre-compute the hashes of the Strings you care about, assign
those values to `static final int' constants, and then
switch (theString.hashCode()) {
case HASH_OF_ABC: ...
case HASH_OF_XYZ: ...
...
}
2) Pre-populate a Map<String,Integer>, look up the String in the
Map, and switch on the Integer value.
3) Like (2), but use an enum.
4) Use polymorphism: Write a class for each String value, use
Class.forName(theString) to load it, and call one of its
methods reflectively.
5) Combine (2/3) and (4): Pre-populate a Map<String,Handler>,
look up the String value, and call a method of the associated
Handler object. (Reflection not required.)
6) Use a chain of "if...else if...else if..."
7) Like (6), but begin with a switch(theString.charAt(0)) to
eliminate many possibilities before starting to compare.
8) Like (7), but with subordinate switches on subsequent chars.
See also "trie."
Personally, I'd pick (6) if the number of interesting String
values was small and well-known, (5) if it were large and/or varying.
De gustibus non disputandum est (Latin for "Don't quarrel with Gus.")
--
Eric Sosman
esosman@ieee-dot-org.invalid