区别与其他的键不能重复的容器,IdentityHashMap允许key值重复,但是——key必须是两个不同的对象,即对于k1和k2,当k1==k2时,IdentityHashMap认为两个key相等,而HashMap只有在k1.equals(k2) == true 时才会认为两个key相等。
看一段代码:
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String,String> map =new IdentityHashMap<String,String>(100);//初始化容器的大小
String a="aa";
String b=new String("aa");
System.out.println(a==b);
map.put(a, "cc");
map.put(b, "bb");
map.put("2", "dd");
System.out.println(map.size());//3
Map<String,String> map1 =new IdentityHashMap<String,String>(100);
map1.put("11", "cc");
map1.put(new String("11"), "bb"); //map1.put(new String("11").intern(), "bb");
map1.put("2", "dd");
System.out.println(map1.size());//3
Map<Integer,String> map2 =new IdentityHashMap<Integer,String>(100);
map2.put(127, "cc");
map2.put(127, "bb");
map2.put(2, "dd");
System.out.println(map2.size());//2
//超出常量池范围~~
Map<Integer,String> map3 =new IdentityHashMap<Integer,String>(100);
map3.put(128, "cc");
map3.put(128, "bb");
map3.put(2, "dd");
System.out.println(map3.size()); //3
}