你可以用
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 appliedreturn value; } else { return map.put(key, value); } } // other methods goes here }另一种选择是制作一个extends类
HashMap,并依赖于其内部实现。Java
1.6源显示
put仅在
putAll中调用
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 appliedreturn value; } else { return super.put(key, value); } } }另一个选项与第一个类似,可以在包含
HashMap实例的类中创建一个实用程序方法,并在需要放置地图的地方调用该方法:
public final Integer putToMap(String key, String value) { if(this.map.containsKey(key)) { return value; } else { return this.map.put(key, value); }}这等效于手动检查的“内联”。



