简体   繁体   中英

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. 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?

you can wrap the hashmap in a class and expose method on that class to add or remove.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM