我是Java的新手,我有一个哈希表,我需要将年龄作为键,计数作为值插入,即
HashMap<Integer,Integer> hashMap = new HashMap<Integer, Integer>();
hashMap.put(1,1);
hashMap.put(2,1);
hashMap.put(3,1);
hashMap.put(1,1); // whenever i insert this ,according to hashmap, it will override, but i want to customise like the value should be incremented , ie the value of key 1 should be 2, again if i insert with
hashMap.put(1,1); // the value of key 1 should be 3.
我希望您可以在添加重复键时自定义覆盖值。我是通过以下方式完成的:
if(hashMap.containsValue(1)){
Integer i = hashMap.get(1);
i++;
hashMap.put(1, i);
}else{
hashMap.put(1, 1);
}
有比这更好的方法吗?请提供建议。
HashMap
的类,并且该类可以提供像get
和put
这样的方法。然后在put
方法中,如果键已经存在于映射中,则可以增加其值。 - TomMultiset
,它快速简便,而且不需要重新发明轮子。 - biziclop