Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean by "the hash table is open" in Java?

I was reading the Java api docs on Hashtable class and came across several questions. In the doc, it says "Note that the hash table is open: in the case of a "hash collision", a single bucket stores multiple entries, which must be searched sequentially. " I tried the following code myself

Hashtable<String, Integer> me = new Hashtable<String, Integer>();
me.put("one", new Integer(1));
me.put("two", new Integer(2));
me.put("two", new Integer(3));
System.out.println(me.get("one"));  
System.out.println(me.get("two"));

the out put was

1
3
  1. Is this what it means by "open"?
  2. what happened to the Integer 2? collected as garbage?
  3. Is there an "closed" example?
like image 274
derrdji Avatar asked Aug 17 '09 15:08

derrdji


1 Answers

No, this is not what is meant by "open".

Note the difference between a key collision and a hash collision.

The Hashtable will not allow more than one entry with the same key (as in your example, you put two entries with the key "two", the second one (3) replaced the first one (2), and you were left with only the second one in the Hashtable).

A hash collision is when two different keys have the same hashcode (as returned by their hashCode() method). Different hash table implementations could treat this in different ways, mostly in terms of low-level implementation. Being "open", Hashtable will store a linked list of entries whose keys hash to the same value. This can cause, in the worst case, O(N) performance for simple operations, that normally would be O(1) in a hash map where the hashes mostly were different values.

like image 178
Avi Avatar answered Nov 09 '22 19:11

Avi