If you have reached this page, I assume you already know what is HashMap and how it works. If you aren't aware of this, I will request you to visit the below links first and then come back to this page.
Let us create a HashMap first and insert some sample values:
Map<Integer , String> myHashMap = new HashMap<>();
myHashMap.put(1, "Value1");
myHashMap.put(2, "Value2");
myHashMap.put(4, "Value3");
System.out.println(myHashMap);
Let us see the output:
{1=Value1, 2=Value2, 4=Value3}
Now, what will happen if we try to enter the same key again?
myHashMap.put(4, "Value4");
The value corresponding to the key will get overridden.
This also proves that we cannot have duplicate keys in hashmap.
Let us see the output:
{null=Value5, 1=Value1, 2=Value2, 4=Value4}
This means we can insert a null key. Let's try to enter one more null key with a different value and see whether the value gets overridden or not.
myHashMap.put(null, "Value6");
Output:
{null=Value6, 1=Value1, 2=Value2, 4=Value4}
Oh Yes !! It is also getting overridden, also it proves that we can only have a single null entry as the key.
So now when we are done with Keys, let's check for some duplicate values.
myHashMap.put(4, "Value6");
myHashMap.put(5, "Value6");
Output.
{null=Value6, 1=Value1, 2=Value2, 4=Value4, 5=Value7, 6=Value7}
So, we have the same value corresponding to multiple keys. ie; we can store duplicate values in HashMap.
Did we just miss something??
Yeah!!! The insertion order of HashMap is not maintained. What if we need to maintain the insertion order?
We will use a LinkedHashMap to preserve the insertion order.
Map<Integer , String> myHashMap = new LinkedHashMapHashMap<>();
THANKYOU :)