[英]What's the right way to build Java Map that is a HashMap but converts values on input and output?
I basically need a slightly modified version of a HashMap
where whenever a value is read or written it needs to be converted.我基本上需要一个稍作修改的
HashMap
版本,每当读取或写入一个值时,都需要对其进行转换。 So far I have tried the following:到目前为止,我已经尝试了以下方法:
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
}
I was hoping that was all I needed to do, but I am struggling with those two methods:我希望这就是我需要做的,但我正在努力使用这两种方法:
Set<Entry<String,Object>> entrySet()
Collection<Object> values()
Those I can't just forward to map as the values need to be converted one by one.那些我不能只转发到 map 因为值需要一一转换。 Of course I could basically copy the implementation from HashMap and modify it to fit my needs, but that seemed to be rather ugly solution and I before I do that I wanted to make sure I am not missing a much nicer solution.
当然,我基本上可以从 HashMap 复制实现并对其进行修改以满足我的需求,但这似乎是一个相当丑陋的解决方案,在我这样做之前,我想确保我不会错过一个更好的解决方案。
Is there any better way?有没有更好的办法?
you can wrap the hashmap in a class and expose method on that class to add or remove.您可以将 hashmap 包装在 class 中,并在该 class 上公开方法以添加或删除。
like this像这样
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();
}
//same way you can add method for remove. //同样的方式你可以添加删除方法。
Take a look at Apache Commons TransformedMap and see if it fits your needs.看看 Apache Commons TransformedMap看看它是否符合您的需求。
What you're doing is per se quite ugly, so I wouldn't worry to death about a slightly ugly implementation.你正在做的事情本身就很丑陋,所以我不会担心稍微丑陋的实现。 Either do what you're suggesting, or else make the get/put methods put the converted values in the map, and then the other methods are just simple wrappers.
要么按照您的建议进行操作,要么让 get/put 方法将转换后的值放入 map,然后其他方法只是简单的包装器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.