Friday, 4 September 2015

Java -Differences between HashSet and HashMap



HashSet
HashMap
1.          HashSet class implements  the Set interface
 HashMap class implements the Map interface
2.          In HashSet we store objects(elements or values) e.g. If we have a HashSet of string elements then it could depict a set of HashSet elements: {“Hello”, “Hi”, “Bye”, “Run”}
 HashMap is used for storing key & value pairs. In short it  maintains the mapping of key & value (The HashMap class is  roughly equivalent to Hashtable, except that it is unsynchronized  and permits nulls.) This is how you could represent HashMap  elements if it has integer key and value of String type: e.g. {1-  >”Hello”, 2->”Hi”, 3->”Bye”, 4->”Run”}
3.          HashSet does not allow duplicate elements that means you can not store duplicate values in HashSet.
 HashMap does not allow duplicate keys however it allows to have  duplicate values.
4.          HashSet permits to have a single null value.
 HashMap permits single null key and any number of null values.

Similarities:

1) Both HashMap and HashSet are not synchronized which means they are not suitable for thread-safe operations unitl unless synchronized explicitly. This is how you can synchronize them explicitly:
HashSet:
Set s = Collections.synchronizedSet(new HashSet(...));
HashMap:
 Map m = Collections.synchronizedMap(new HashMap(...));
3)      Both of these classes do not guarantee that the order of their elements will remain constant over time.

No comments:

Post a Comment