简体   繁体   中英

Java Generics - How do I call a generic map with a successor object

I wrote the following method

 validate(Map<String,IAnimal> map)

And I want to call it with

dogMap = new HashMap<String,Dog>;
...
validate(dogMap)

where Dog is the successor of Animal,
But it does not compile.
How do I change it so I could call it with a successor object? Thanks.

You can change the signature of validate to :

validate(Map<String,? extends IAnimal> map)

This will allow you to pass any map with a String key and a value that extends or implements IAnimal .

You have to declare the method with type boundaries:

validate(Map<String,? extends IAnimal> map)

See http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html for further explanations of Java (Bounded) Wildcards.

You have two options:

  1. Change the signature of validate to YourReturnType validate(Map<? extends String, ? extends IAnimal> map) (assuming you do not want to add elements to it).
  2. Create a new Map<String, IAnimal> from the dogMap you want to pass: new HashMap<String, IAnimal>(dogMap) and pass that object to validate .

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