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 方法。此类设计仅用于其中需要引用相等性语义的罕见情况。

IdentityHashMap类利用哈希表实现Map接口,比较键(和值)时使用引用相等性代替对象相等性。我们来看看这个类的代码吧:

public class test1 {

public

static void main(String[] args) {

String str1 = "abc";

String str2 = "abc";

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

Map map = new IdentityHashMap();

map.put(str1, "hello");

map.put(str2, "world");

for(Entry entry : map.entrySet())

{

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

}

System.out.println("containsKey---> " +

map.containsKey("abc"));

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

}

}

这端代码输出的结果如下:

true

abc world

containsKey---> true

value----> world

为什么我们的Key还是只保存了一个值????这个问题和《java解惑第62题一样》书上面是这样解释的,我们来看看:

语言规范保证了字符串是内存限定的,换句话说,相等的字符串常量同时也是相同的对象。这可以确保在我们的程序中第二次出现的字符串字面常量“abc”引用到了与第一次相同的String实例上,因此尽管我们使用了一个IdentityHashMap来代替诸如HashMap这样的通用目的的Map实现,但是对程序的行为却不会产生任何影响。

我们来看看下面的代码就可以实现一个key保存两个value的情况。我们的代码如下:

public class test1 {

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

map.put(str1, "hello");

map.put(str2, "world");

for(Entry entry : map.entrySet())

{

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

}

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

System.out.println("str1 containsKey---> " +

map.containsKey(str1));

System.out.println("str2 containsKey---> " +

map.containsKey(str2));

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

System.out.println("str1 value----> " +

map.get(str1));

System.out.println("str2 value----> " +

map.get(str2));

}

}

我们的看看输出的结果为:

false

abc world

abc hello

containsKey---> false

str1 containsKey---> true

str2 containsKey---> true

value----> null

str1 value----> hello

str2 value----> world

我们可以知道IdentityHashMap是靠对象来判断key是否相等的,如果我们一个key需要保存多个value的时候就需要使用到这个IdentityHashMap类,这样我们我们就可以需要的时候使用到这个类了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值