如何在hashmap中保留重复项

mmvthczy  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(374)

我不需要删除重复项。。

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);

有没有办法在hashmap中保留副本?如果不是,我应该怎么做(我应该使用什么接口或类)如果我想这样做?

3ks5zfa0

3ks5zfa01#

HashMap 不能有多个具有相同属性的元素 key . 尝试使用 ArrayList 取而代之的是:

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());

输出:

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

相关问题