Home > Java > The difference between HashTable and HashMap

The difference between HashTable and HashMap

HashTable is widely used, HashMap is the class used to take the place of HashMap in the new framework, this means sun suggests to use HashMap instead of HashTable. Maybe you think HashTable works well, why not?

I’d like to talk something about the difference between HashTable and HashMap.

 

1. The method of HashTable is synchronized, but HashMap is not, so when we use HashMap in multi-thread, we need to handle the thread synchronization carefully, just like Vector and ArrayList.

2. NULL value is not allowed in HashTable(Both Key and Value are not allowed), but HashMap allows NULL value(Both Key and Value)

3. There is a method called contains(Object value) in HashTable, it has the same function with method called containsValue(Object value) in HashMap.

4. HashTable uses Enumeration to iterate it’s elements, but HashMap uses Iterator.

5. The default size of hash array is 11 in HashTable, to extend old*2 + 1, In HashMap, the default size is 16, and it should be exponential ramp by 2.

6. The use of hash value is different, HashTable uses the object’s hashCode directory, the code is like this:

int hash = key.hashCode();

int index = (hash & 0x7FFFFFFF)%tab.length;

but HashMap need to recalculate hash value

int hash =  hash(k);

int i= indexFor(hash,table.length);

static int hash(Object x){

int h = x.hashCode();

h+= ~(h << 9);

h^=(h>>>14);

h+=(h<<4);

h^=(h>>>10);

return h;

}

static int indexFor(int h,int length){

return h&(length-1);

}

Categories: Java Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Powered by WP Robot