特殊的Map类-IdentityHashMap与HashMap的区别
java.util.Map的一个实现类是IdentityHashMap,可以根据地址判断key是否相等:
public class IdentityHashMap
extends AbstractMap
implements Map
This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)
This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map’s general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.
package com.mldn;
import java.util.Map;
import java.util.IdentityHashMap;
import java.util.HashMap;
import java.util.Set;
import java.util.Iterator;
public class IdentityDemo
{
public static void main(String[] args)
{
Map
map = new IdentityHashMap
map.put(new Person(“张三”, 20), “zhangsan”); // 添加实体
map.put(new Person(“张三”, 20), “zhangsan”); // 添加内容相同的实体
Set
Iterator
while (iter.hasNext())
{
Map.Entry
System.out.println(me.getKey() + “–>” + me.getValue()); // 输出实体
}
System.out.println(“IdentityHashMap输出完毕!”);
map = new HashMap
map.put(new Person(“张三”, 20), “zhangsan”); // 添加实体
map.put(new Person(“张三”, 20), “zhangsan”); // 添加内容相同的实体
entry = map.entrySet(); // 获取所有实体
iter = entry.iterator(); // 获取所有实体的迭代器
while (iter.hasNext())
{
Map.Entry
System.out.println(me.getKey() + “–>” + me.getValue()); // 输出实体
}
}
}
/*
ubuntu@xu-desktop:~$ java com.mldn.IdentityDemo
// 前提:Map对重复的key不会添加到Map对象中!Person类必须正确覆写了hashCode,equals方法!
姓名:张三年龄:20–>zhangsan
姓名:张三年龄:20–>zhangsan
IdentityHashMap输出完毕!
姓名:张三年龄:20–>zhangsan
// 发现IdentityHashMap并不排除内容相同的实体,而HashMap排除内容相同的实体;
// IdentityHashMap判断实体是否重复的标准是:key对象的内存地址是否相同,内容不是标准;
// HashMap则是根据key对象的内容是否相同判断实体是否重复了!
*/
声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 嗅谱网
转载请注明:转自《特殊的Map类-IdentityHashMap与HashMap的区别》
本文地址:http://www.xiupu.net/archives-123.html
关注公众号:
微信赞赏
支付宝赞赏