Difference between HashSet HashMap

Difference between HashSet HashMap

Answer: Below are the differences:

HashSet HashMap
HashSet implements Set interface and it is backed by hash table (actually HashMap instance) HashMap is a Hash table based implementation of Map interface
HashSet store objects HashMap store object as key and value pair
HashSet doesn’t allow duplicate element but null values are allowed HashMap does not allows duplicate key but null key and values are allowed
This interface doesn’t guarantee that order will remain constant over the time Ordering of the element is not guaranteed over the time

Please have java class example below:

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


public class HashSetMapTest {

    public static void main(String[] args) {
    
    HashMap<String, String> hashMap = 
        new HashMap<String, String>();
    hashMap.put("Java", "Java");
    hashMap.put("Honk", "Honk");
    hashMap.put("Test", "Test");
    hashMap.put("Test", "Test");
    hashMap.put(null,null);
    hashMap.put("abc",null);
    hashMap.put("def",null);
    System.out.println("HashMap example:\n");
    Set<Entry<String, String>> set = hashMap.entrySet();
    for (Entry<String, String> entry : set) {
        
        System.out.println("Key: "+entry.getKey()
            +" Value: "+entry.getValue());      
    }
    
    System.out.println("\nHashMap example:\n");
    
    HashSet<String> hashSet = new HashSet<String>();
    hashSet.add("Java Honk");
    hashSet.add("Java Honk");
    hashSet.add(null);
    hashSet.add(null);
    
    for (String string : hashSet) {
        System.out.println("Value: "+string);
        
    }
    
    }

}

Output:

Difference between HashSet HashMap

 

Leave a Reply

Your email address will not be published. Required fields are marked *