简体   繁体   English

Java泛型-如何使用后继对象调用泛型映射

[英]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的签名更改为:

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 . 这将允许您传递带有String键和扩展或实现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. 有关Java(有界)通配符的进一步说明,请参见http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html

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). validate的签名更改为YourReturnType validate(Map<? extends String, ? extends IAnimal> map) (假设您不想向其添加元素)。
  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 . 从要传递的dogMap创建一个新的Map<String, IAnimal>new HashMap<String, IAnimal>(dogMap)并将该对象传递给validate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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