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

后端 未结 3 2026
走了就别回头了
走了就别回头了 2021-01-29 11:19

I wrote the following method

 validate(Map map)

And I want to call it with

dogMap = new HashMap

        
相关标签:
3条回答
  • 2021-01-29 11:53

    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.

    0 讨论(0)
  • 2021-01-29 11:57

    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.

    0 讨论(0)
  • 2021-01-29 12:01

    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.
    0 讨论(0)
提交回复
热议问题