Tuesday 26 March 2013

Diffrence between hashtable and hashmap?

1) Hashtable and Hashmap are different in the sense that Hashmap is synchronized and permits nulls as keys as well as values. Hashtable requires non-null values for keys as well as values.
a. In case iteration performance is important, keep the capacity/size of hashmap small because the time for iteration is proportional to the capacity + size. However, get() and put() have constant time performance.

b. The load factor and initial capacity effect the performance of the hashmap. When the number of entries in the hashmap exceed the product of load factor and current capcity, the hashmap is rehashed so as to have twice the number of buckets. A value of 0.75 for load factor is good tradeoff between time and space cost.

c. The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

d. The parameterized constructors are allow for specifying the initial capacity and/or load factor.

e. The hashmap is not synchronized for structural changes (addition and deletion of keys) and not for operations like updating the value for a key. Collections.synchronizedMap should be used for synchronized access.

f. The iterator returned is fail-fast i.e. as soon as the map is structurally modified using other than iterator’s remove method, the iterator throws ConcurrentModificationException. However, the fail-fast behaviour is not guaranteed.

g. The put method returns null if either there was no such key in the map or the value associated with the key was null or it returns the previous value associated with key, if it exists in the map.

h. Similar is the case with get(), it returns null if either there is no key with name specified or the key explicitly maps to null. The containsKey can be used to distinguish these two cases.

No comments:

Post a Comment