构建作为 HashMap 但在输入和输出上转换值的 Java Map 的正确方法是什么?
我基本上需要一个稍微修改过的 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()
我不能直接转发到地图,因为值需要一一转换。当然,我基本上可以从 HashMap 复制实现并修改它以满足我的需要,但这似乎是相当丑陋的解决方案,在我这样做之前我想确保我没有错过一个更好的解决方案。
还有更好的办法吗?
I basically need a slightly modified version of a HashMap
where whenever a value is read or written it needs to be converted. 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. 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.
Is there any better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将哈希图包装在一个类中,并公开该类上的方法以进行添加或删除。
像这样
//同样的方式你可以添加删除方法。
you can wrap the hashmap in a class and expose method on that class to add or remove.
like this
//same way you can add method for remove.
看看 Apache Commons TransformedMap并看看它是否符合您的需求。
Take a look at Apache Commons TransformedMap and see if it fits your needs.
你所做的事情本身就很丑陋,所以我不会担心一个稍微丑陋的实现。要么按照您的建议进行操作,要么让 get/put 方法将转换后的值放入映射中,然后其他方法只是简单的包装器。
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.