一种可以key让重复的Map数据结构IdentityHashMap

IdentityHashMap:如果key为对象的时候,那么key可以重复。如果key是字符串常量池的内容,那么key不可以被重复,跟HashMap没区别。

1.先看HashMap的效果

Map<String,String> map = new HashMap<>();
map.put(new String("hjx"),"123");
map.put(new String("hjx"),"123");
map.put(new String("hjx"),"123");

ArrayList<String> keys = new ArrayList<>();
ArrayList<String> values = new ArrayList<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    keys.add(key);
    values.add(value);
}
System.out.println(keys);    //[hjx]
System.out.println(values);  //[123]

2.把HashMap改为IdentityHashMap

Map<String,String> map = new IdentityHashMap<>();
map.put(new String("hjx"),"123");   //必须new String(),需要的是对象
map.put(new String("hjx"),"123");
map.put(new String("hjx"),"123");

ArrayList<String> keys = new ArrayList<>();
ArrayList<String> values = new ArrayList<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    keys.add(key);
    values.add(value);
}
System.out.println(keys);    //[hjx, hjx, hjx]
System.out.println(values);  //[123, 123, 123]

3.如果key为普通字符串,那么key不能被重复

Map<String,String> map = new IdentityHashMap<>();
map.put("hjx","123");   //必须new String(),需要的是对象
map.put("hjx","123");
map.put("hjx","123");

ArrayList<String> keys = new ArrayList<>();
ArrayList<String> values = new ArrayList<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    keys.add(key);
    values.add(value);
}
System.out.println(keys);    //[hjx]
System.out.println(values);  //[123]

你可能感兴趣的:(java,java,map)