1

We can insert duplicate key using org.apache.common.collections.MultiValuesMap except it.

Is there any way to insert duplicate key into Map implemented class?

If yes,how to work that class get() method?

1 Answers1

0

Yes, We can insert duplicate key into IdentityHashMap class.

get() method check below condition:

if (key1==null ? key2==null : key1.equals(key2)).) 

if you try to retrieve value using same key reference with which value was inserted, you will get the value. But if you try to get value using difference key reference (even if it is equal), you will get null.

Example:

// Created IdentityHashMap objects
 Map ihm = new IdentityHashMap();
// Inserting keys and values in IdentityHashMap Object
ihm.put(new String("key"), "RI Equation");
ihm.put(new String("key"), "Maxxton");

String rikey = new String("identityKey");
String mkey = new String("identityKey");

ihm.put(rikey, "RI Equation");
ihm.put(mkey, "Maxxton");

// Print IdentityHashMap after adding keys
System.out.println("IdentityHashMap after adding key :" + ihm);
System.out.println("Getting value from IdentityHashMap :"+ ihm.get("identityKey"));
System.out.println("Getting value from IdentityHashMap :"+ ihm.get(rikey));
System.out.println("Getting value from IdentityHashMap :"+ ihm.get(mkey));
azro
  • 53,056
  • 7
  • 34
  • 70
  • @sachingajbhiye as per question description there is no exact answer in above link then why it is marked as duplicate. – RIEquation Consultancy Oct 25 '20 at 09:20
  • by mistake I acknowledge as duplicate, your ans I was expecting.. – sachin gajbhiye Oct 25 '20 at 09:24
  • Although your answer is technically correct, I do not think it has any practical application. You must always pass the references to the identical keys. As a result I could also store the correct value in a variable. – Marcinek Oct 25 '20 at 09:37