我有一个HashMap如下(假设它有10,0000个元素)
HashMap<String,String> hm = new HashMap<String,String>();
hm.put("John","1");
hm.put("Alex","2");
hm.put("Mike","3");
hm.put("Justin","4");
hm.put("Code","5");
==========================
Expected Output
==========================
Run Code Online (Sandbox Code Playgroud)
Key = John",Value = "1"
Key = Alex",Value = "2"
Key = Mike",Value = "3"
Key = Justin",Value = "4"
Key = Code",Value = "5"
===========================
我需要Java代码来防止Addition of Duplicate <Key,Value> Pairs在HashMap中
满足以下条件.
1> hm.put("John","1"); is not accepted/added again in the Map
2>hm.put("John","2"); is not accepted/added again in the Map
希望清楚.提供的Java代码将不胜感激.(因为我可以向现有地图添加任何副本,所以需要通用解决方案)
你可以用HashMap一个类,它代表put,get以及其他的方法你使用HashMap.这种方法是一种浪费,但安全的,因为它不依赖于内部实现HashMap,AbstractMap.下面的代码说明put,get委托:
public class Table {
protected java.util.HashMap<String, Integer> map =
new java.util.HashMap<String, Integer>();
public Integer get(String key) { return map.get(key); }
public Integer put(String key, Integer value) {
if (map.containsKey(key)) {
// implement the logic you need here.
// You might want to return `value` to indicate
// that no changes applied
return value;
} else {
return map.put(key, value);
}
}
// other methods goes here
}
Run Code Online (Sandbox Code Playgroud)
另一个选择是创建一个扩展的类HashMap,并依赖于它的内部实现.Java 1.6源代码显示put只在putAllin中调用HashMap,因此您可以简单地覆盖put方法:
public class Table extends java.util.HashMap<String, Integer> {
public Integer put(String key, Integer value) {
if (containsKey(key)) {
// implement the logic you need here.
// You might want to return `value` to indicate
// that no changes applied
return value;
} else {
return super.put(key, value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
另一个选项类似于第一个选项,并且可以在您的类中创建一个包含HashMap实例的实用程序方法,并在您需要向地图放置内容时调用该方法:
public final Integer putToMap(String key, String value) {
if(this.map.containsKey(key)) {
return value;
} else {
return this.map.put(key, value);
}
}
Run Code Online (Sandbox Code Playgroud)
这是手动检查的"内联"等价物.