Thread Closed

How do you use Java's Hashtable?

 
Share Thread Thread Tools
Oct14-06, 05:05 PM   #18
 
Recognitions:
Gold Membership Gold Member
Science Advisor Science Advisor
Retired Staff Staff Emeritus

How do you use Java's Hashtable?


It seems that a difference between the way I was using HashMap and the way HashSet uses HashMap, is that I was doing a containsValue() check and HashSet does a containsKey() check on its internal HashMap. This may account for the performance difference, though it doesn't make total sense to me why it should.
Ye gads, that would do it. "containsValue" has to do a brute force search through the entire HashMap until it finds the desired value or reaches the end. And since you initialized it to have a very large capacity...
 
Oct14-06, 05:17 PM   #19
 
Recognitions:
Science Advisor Science Advisor
Yeah, I guess. It's kind of annoying that they have a containsValue() method in the first place when there's no efficient implementation behind it! It should be marked "deprecated."
 
Oct14-06, 05:36 PM   #20
 
Recognitions:
Gold Membership Gold Member
Science Advisor Science Advisor
Retired Staff Staff Emeritus
It makes sense from both a consistency and convenience viewpoint: every other container class (even ArrayList, for example) implements a contains(Object) method. And searching for a value is something one would sometimes want to do. Map.values().contains(Object) is awkward syntax, and probably execlutes more slowly for most Map types. Some Map classes might even have efficient value lookups, and it would be a shame to force the user to break the container abstraction to access such a useful method.
 
Oct14-06, 05:55 PM   #21
 
Recognitions:
Science Advisor Science Advisor
Well, if someone needs a hash table then chances are they have thousands of values and they want whatever they are doing to be fast. A linear search in that situation is not practical. values().contains() at least makes the programmer aware of how inefficient it is--it's awkward and should be awkward. In terms of consistency, HashMap does have a containsKey() method, and it does not have a plain contains() method anyway (and shouldn't because it would be ambiguous). One contains-like method would be enough. In the API there isn't even a warning about the time complexity of containsValue() and the documentation is fairly vague about what's actually going on there. As you say, there could be alternate implementations that do have fast lookup for values. It should mention that this is not one of them. Deprecating this particular method in this particular class would be sensible--it is a good idea to deprecate linear time access on a likely large set, or at least mention it in the API.
 
Thread Closed
Thread Tools


Similar Threads for: How do you use Java's Hashtable?
Thread Forum Replies
Hashtable for booleans? Programming & Comp Sci 18
Java's "Scanner" Computing & Technology 6