![](/img/trans.png)
[英]Java: What's the right way of writing a generic HashMap merge method?
[英]What's the right way to build Java Map that is a HashMap but converts values on input and output?
我基本上需要一個稍作修改的HashMap
版本,每當讀取或寫入一個值時,都需要對其進行轉換。 到目前為止,我已經嘗試了以下方法:
public class MyMap implements Map<String, Object> {
private HashMap<String, MyType> map;
public Object get(Object key) {
return map.get(key).getValue();
}
public Object put(String key, Object value) {
return map.put(key, MyType.wrap(value)).getValue();
}
... all other methods of the Map interface are handled by map
}
我希望這就是我需要做的,但我正在努力使用這兩種方法:
Set<Entry<String,Object>> entrySet()
Collection<Object> values()
那些我不能只轉發到 map 因為值需要一一轉換。 當然,我基本上可以從 HashMap 復制實現並對其進行修改以滿足我的需求,但這似乎是一個相當丑陋的解決方案,在我這樣做之前,我想確保我不會錯過一個更好的解決方案。
有沒有更好的辦法?
您可以將 hashmap 包裝在 class 中,並在該 class 上公開方法以添加或刪除。
像這樣
Class MyHashmap {
private Map map = new HashMap();
//methods for add/remove to wrap and put in HashMap
public void add(String ,Object) {
map.put(key, MyType.wrap(value)).getValue();
}
//同樣的方式你可以添加刪除方法。
看看 Apache Commons TransformedMap看看它是否符合您的需求。
你正在做的事情本身就很丑陋,所以我不會擔心稍微丑陋的實現。 要么按照您的建議進行操作,要么讓 get/put 方法將轉換后的值放入 map,然后其他方法只是簡單的包裝器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.