What is the BEST way to iterate through Hashtable entries WITHOUT the java.lang.Map APIs?
I am working on a BlackBerry j2me Java implementation that does not have the Collections API. So there is no entrySet()
method or Map.Entry
class. The only available methods to iterate through the mappings of a Hashtable
are the elements()
and keys()
methods.
Can I expect elements()
and keys()
to return the same number of mappings, in the same order? If so, I can do the following:
Enumeration keys = table.keys();
Enumeration elements = table.elements();
String key, value;
while(keys.hasMoreElements()) {
key = keys.nextElement();
value = elements.nextElement();
}
I would think this is the case, but the docs don't say for sure. If I can't make this assumption, then I will have to iterate t开发者_Python百科hrough the keys only:
Enumeration keys = table.keys();
String key, value;
while(keys.hasMoreElements()) {
key = keys.nextElement();
// Less efficient b/c I have to do a lookup every time.
value = table.get(key);
}
Edit: You can assume only one thread has access to the table.
They are guaranteed to return the same number of items. And in Sun's implementation, keys and values are returned in the same order. (In fact, under the covers, the same class serves to iterate over keys, values or Map.Entry objects.) Indeed, it's hard to imagine getting the values in some way other than by iterating over the buckets.
However, the language specification doesn't say they have to be in the same order, so if you make that assumption, you will hinder portability and possibly introduce hard-to-find bugs later on. I think it was the algorithms expert Donald Knuth who said, "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." Unless that particular part of the code is a huge bottleneck, I recommend you do the lookup for each key.
精彩评论