在正常的map操作中,key是不能重復的,如果希望key的內容可以重復,可以用IdentityHashMap
舉個栗子
輸出結果:
public static void main(String[] args) { Map<String,String> map = new HashMap<>(); map.put("姓名","小明"); map.put("姓名","小紅"); map.put("姓名","張三"); map.put("姓名","李四"); System.out.println("普通map:"+map); Map<String, String> IdentityHashMap = new IdentityHashMap<>(); IdentityHashMap.put(new String("name"),"路飛"); IdentityHashMap.put(new String("name"),"小叮當"); IdentityHashMap.put(new String("name"),"聖斗士"); System.out.println("key可重復map:"+IdentityHashMap); }