英文:
How to keep duplicates in HashMap
问题
我不需要移除重复项..
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 中保留重复项?如果没有,如果我想要保留重复项,我应该做什么(应该使用哪个接口或类)?
英文:
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?
答案1
得分: 1
一个 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]]
英文:
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]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论