I can’t help noticing that I’m using quite a lot of string comparisons while parsing a well defined XML file in Android (with a XmlPullParser).
As of now it typically looks something like this (somewhat simplified):
...
tag = parser.getName().toLowerCase();
if ("tag1".equals(tag)) {
// Do something with the state machine
}
else if ("tag2".equals(tag)) {
// Do something else with the state machine
}
...
else if ("tag23".equals(tag)) {
// Do something more with the state machine
}
What I would like to have instead is something like this (where StringMatcher would be the hypothetical happy-maker for me):
private static final StringMatcher tagMatcher = new StringMatcher(StringMatcher.NO_MATCH);
static {
tagMatcher.addString("tag1", 1);
tagMatcher.addString("tag2", 2);
....
tagMatcher.addString("tag23", 23);
}
...
tag = parser.getName().toLowerCase();
switch (tagMatcher.match(tag)) {
case 1:
// Do something with the state machine
break;
case 2:
// Do something else with the state machine
break;
...
case 23:
// Do something more with the state machine
break;
default:
Log.e("PARSER", "Unexpected tag: " + tag);
break;
}
As you see I would like a UriMatcher pattern applied to my XML file tags. Do any of you know of such a class I can use in Android? Any other fast filtering on strings would do as well (it would be neat, though, if the UriMatcher-pattern could be reused).
So far I’ve been looking at regular expressions but I’m not really sure I can fit it to my needs (I would like a switch – case style test) and, of course, the regular string comparison as shown in above example.
Cheers,
— dbm
You can either use a
HashMapsince that does not need to iterate over the whole array to find the match valueor you can use a
SparseIntArrayusing the same hash approach. Advantage here is that you don’t need to boxintintoIntegerwhich should result in a slight speed / memory advantage.This is doing binary search instead of iterating over the whole thing like
SparseArray#indexOfValue(t)does. Note that there is a chance of hash collisions in this approach.I think using an approach like that is faster than a long chain of
if (equals) else if (equals)for larger amounts of comparisons. Theif .. else ifapproach needs to checkString.equals()every time which boils down to comparing all characters of the strings while a hash based approach needs to calculate the hash value just once and can do a binary search over all known hash values then.