简体   繁体   中英

How to keep duplicates in HashMap

I need not to remove duplicates ..

HashMap<Integer,String> hm=new HashMap();
hm.put(3,"aba");
hm.put(4,"abab");
hm.put(3,"aba");
hm.put(3,"aba");
System.out.println(hm);

Is there any way to keep duplicates in HashMap ? If not what should I do(what interface or class should i use ) if I want to do so?

A HashMap cannot have multiple elements with the same key . Try using an ArrayList instead:

public class Item implements Comparable<Item>{
    private int num;
    private String name;
    public Item(int num, String name) {
        this.setNum(num);
        this.setName(name);
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Item [num=" + num + ", name=" + name + "]";
    }
    @Override
    public int compareTo(Item other) {
        return this.num-other.num;
    }
}
List<Item> list=new ArrayList<>();
list.add(new Item(3,"aba"));
list.add(new Item(4,"abab"));
list.add(new Item(3,"aba"));
list.add(new Item(3,"aba"));
Collections.sort(list);
System.out.println(list.toString());

Output:

[Item [num=3, name=aba], Item [num=3, name=aba], Item [num=3, name=aba], Item [num=4, name=abab]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM