哪个实现了Map接口的类允许插入重复的键对象?

huangapple go评论71阅读模式
英文:

Which Map implemented class allow to insert duplicate key object?

问题

我们可以使用org.apache.common.collections.MultiValuesMap插入重复键,除非它。

是否有任何方法可以将重复键插入到Map实现类中?

如果是的,该类的get()方法如何工作?

英文:

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

得分: 0

是的,我们可以将重复的键插入到IdentityHashMap类中。

get() 方法检查以下条件:

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

如果您尝试使用与插入值时使用的相同键引用来检索值,您将获得该值。但是,如果您尝试使用不同的键引用来获取值(即使它们相等),您将获得null。

示例:

// 创建 IdentityHashMap 对象
Map ihm = new IdentityHashMap();
// 向 IdentityHashMap 对象插入键和值
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");

// 在添加键之后打印 IdentityHashMap
System.out.println("添加键后的 IdentityHashMap:" + ihm);
System.out.println("从 IdentityHashMap 获取值:" + ihm.get("identityKey"));
System.out.println("从 IdentityHashMap 获取值:" + ihm.get(rikey));
System.out.println("从 IdentityHashMap 获取值:" + ihm.get(mkey));
英文:

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));

huangapple
  • 本文由 发表于 2020年10月25日 16:35:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64521811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定