Search code examples
javajava-8hashmapconcurrenthashmaplinkedhashmap

Can we create hashmap key singleton?


I was giving interview one other day and i was speechless when questioning is done on hashmap Here are few

Can we make key as singleton?

Can we make key of hashmap mutable or immutable which one you will choose and why?

For second question i searched through web and found that if we are creating key it should be immutable otherwise data saved on first key and then modified later and if we try to get it again it will give null thus object will be lost. Here is the link that i followed for this Custom Key Hashmap

What about the first question Can we create Hashmap key singleton, according to me if we create key singleton then we lose power of hashmap using same key will replace data if we try to add using singleton key.

Please throw some light on it.


Solution

  • hmm, That's interesting.

    First the Singleton Class in Java, is a class that can have only one object (an instance of the class) at a time. that means only one copy shared between multiple Objects.

    We have two objects of Singleton class

    Singleton x = Singleton.getInstance(); 
    Singleton y = Singleton.getInstance(); 
    

    Scenario 1 : If we create HashMap with Singleton key then

    Map<SingletonClass, Interger> map = new HashMap<>();
            map.put(x, 10);
            map.put(y, 20);
    

    What do you think the output will be, size would be 1 in this case and 10 is override by 20. Right? Same object have same HashCode and equals method implementation.

    Scenario 2 : what If one objectjust change the field's value of Singleton class

    Map<SingletonClass, Interger> map = new HashMap<>();
        map.put(x, 10);
        y.s = (y.s).toUpperCase(); // s is a String field in Singleton Class
        map.put(y, 20);
    

    in this case size would be 1. same hashcode for x and y.

    So, there is always 1 object it will override the value again and again.

    And as you know why we use Immutable class as a key. It's now clear that you can't use the Singleton class in a HashMap as a key.

    Even If you override the HashCode Object as a key is stored as a reference in Map. So If you change its implementation it's get reflected in the Map while executing the hashcode method of Singleton Class. Yes you can Override the equals method but it will increase the collision cases in HashMap only.