Reputation: 53
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?
Upvotes: 2
Views: 91
Reputation: 28414
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]]
Upvotes: 1