Friday, June 17, 2016

Hashtable , HashMap, Set , List differences java

What is difference between HashMap and Hashtable?
Ans:

HashMap= HashMap is not synchronized.In case of single thread, using HashMap is faster than than the Hashtable. HashMap allows null keys and null values to be stored.Iterator in the HashMap is fail-fast.This means Iterator will produce exception if concurrent modifications are made to the HashMap.

Hashtable=Hashtable is synchronized by default.In case of multiple threads,using Hashtable is advisable.With a single thread ,Hashtable becomes slow. Hashtable does not allow null keys or values.Enumeration for the Hashtable is not fail-fast.This means even if concurrent modifications are done to Hashtable ,there will not be any incorrect results produced by Enumeration.

Can you make HashMap synchronized?
Ans:
Yes,we can make it using synchronizedMap() methods as shown:

Collections.synchronizedMap(new HashMap());

What is difference between a Set and a List?
Ans:

Set= A set represent a collection of elements.Order of the element may change in the set.Set will not allow duplicate values to be stored.Accessing elements by their index is not possible. Sets will not allow null elements.

Lists= A List represents ordered collection of elements.List preserves the order of elements in which they are entered.List will allow duplicate values.Accessing elements by index is possible.Lists allow null elements to be stored.

No comments: