java map 允许重复_Java 支持重复key的map

我们平时使用的Map,都是只能在Map中保存一个相同的Key,我们后面保存的相同的key都会将原来的key的值覆盖掉,如下面的例子。

public class test {

public

static void main(String[] args) {

String str1 = new String("abc");

String str2 = new String("abc");

System.out.println(str1 == str2); //false

Map map = new HashMap();

map.put(str1, "hello");

map.put(str2, "world");

for(Entry entry :map.entrySet())

{

System.out.println(entry.getKey()+" " + entry.getValue());

}

System.out.println("---->" + map.get("abc"));

}

}

这个例子中我们可以看见相同的key只能保存一个value值,下面我们来看一种map可以实现一个key中保存多个value。这个map也就是IdentityHashMap。下面我们就来介绍下IdentityHashMap这个类的使用。

API上这样来解释这个类的:此类不是通用Map实现!此类实现Map接口时,它有意违反Map的常规协定,该协定在比较对象时强制使用

equals


版权声明:本文为weixin_39886956原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。