I have the following class:
class DerivedMap extends Hashmap<String,Object>
{}
Which I use because I want to implement some custom actions for this type of map.
I then pass instances of this class to an external api that wants Map, this naturally works well.
The problem is that I also get Map instances as return values from the api. Since a real object hides behind the interface that the api chose I know I cannot just cast it.
So, how do I convert Map to my custom DerivedMap? Must I ma开发者_运维技巧nually copy all the keys/values?
Thanks.
You could create a constructor like this:
class DerivedMap extends HashMap<String, Object> {
public DerivedMap(Map<String, Object> map) {
super(map);
}
}
and then create a DerivedMap
from a Map
like this:
derivedMap = new DerivedMap(otherMap);
The super(map)
invokes the HashMap
constructor that copies all mappings of the argument map to the newly created map. From the docs:
Constructs a new HashMap with the same mappings as the specified Map.
精彩评论