Java: Hashtable stores multiple items with same hash in one bucket -
problem description
while reading oracle documentation hashtable found "in case of "hash collision", single bucket stores multiple entries, must searched sequentially", seek find method homecoming me items sequentially, if have 2 items same hash, can't find in documentation. in order reproduce situation seek write simple code, can find below.
oracle documentation hashtablean instance of hashtable has 2 parameters impact performance: initial capacity , load factor. capacity number of buckets in hash table, , initial capacity capacity @ time hash table created. note hash table open: in case of "hash collision", single bucket stores multiple entries, must searched sequentially. load factor measure of how total hash table allowed before capacity automatically increased. initial capacity , load factor parameters simply hints implementation. exact details when , whether rehash method invoked implementation-dependent.
simple codeclass key { public final int mid; public key(int id) { mid = id; } @override public int hashcode() { if(mid == 1 || mid == 2) { system.out.println("have same hashcode()"); homecoming 5673654; } homecoming super.hashcode(); } }; public class hashtabletest { public static void main(string... args) { hashtable<key, string> dict = new hashtable<key, string>(); dict.put(new key(1), "one"); dict.put(new key(2), "two"); system.out.println(dict.size()); // prints 2 system.out.println(dict.get(new key(1))); // prints null } };
in code above seek add together hashtable 2 items have same hashcode (anyway think have :) ), create key
class , override it's hashcode
method, useless can't item hashtable , think items not added sequentially.
the hashtable
(and hashmap
) implement collision resolution storing multiple keys map same bucket number.
however, need override equals
method in key
. hashtable
(or hashmap
) find key exists in map, hash codes used find bucket, equals
used distinguish distinct keys in same bucket. because aren't overriding equals
, key
inherits equals
object
, determines if 2 objects same object, not whether contents equal.
the equals method class object implements discriminating possible equivalence relation on objects; is, non-null reference values x , y, method returns true if , if x , y refer same object (x == y has value true).
note necessary override hashcode method whenever method overridden, maintain general contract hashcode method, states equal objects must have equal hash codes.
java hashtable
No comments:
Post a Comment