HashSet VS HashMap in java

In this section we will learn and know what difference HashSet and HashMap in java .

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 Example:

Set cset =  Collections.synchronizeSet( new HashSet(....));

HashMap Example: 

Map m = Collections.synchronizeMap(new HashMap());

2) Both of these classes do not guarantee that the order of their elements will remain constant over time.

3) If you look at the source code of HashSet then you may find that it is backed up by a HashMap. So basically it internally uses a HashMap for all of its operations.

4) They both provide constant time performance for basic operations such as adding, removing element etc.



See Example :

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

public class Example1 {
 public static void main(String args[]) {
     // HashSet declaration
     HashSet<String> hashset  =  new HashSet<String>();

     // Adding elements to the HashSet
     hashset.add("Item4");
     hashset.add("Item2");
     hashset.add("Item6");
     hashset.add("Item1");
     hashset.add("Item3");
     hashset.add("Item5");
     System.out.println("HashSet values :"+hashset);
   
     //HashMap Declaration
     Map<String, String> map = new HashMap<String, String>();
     map.put("1", "Book1");
     map.put("2", "Book2");
     map.put("3", "Book3");
     map.put("4", "Book4");
     System.out.println("HashMap values : "+map);
 
 }
}

//result:

HashSet values :[Item1, Item2, Item5, Item6, Item3, Item4]
HashMap values : {1=Book1, 2=Book2, 3=Book3, 4=Book4}












EmoticonEmoticon