java如何在映射中找到值的类型?
如果你有这样的东西:
public abstract class Animal {...}
public class Dog extends Animal {...}
public class Cat extends Animal {...}
Map<Integer, Animal> dogs = getSomeDogs();
Map<Integer, Animal> cats = getSomeCats();
private Map<Integer, Dog> specificDogs;
public Map<Integer, Dog> specificallyGetSomeDogs();
{
return this.specificDogs;
}
您可以看到,有一个方法getSomeDogs()
返回泛型Map<Integer, Animal>
对象
我的方法specificallyGetSomeDogs()
需要返回一个Map<Integer, Dog>
如何将getSomeDogs()
的结果转换为Map<Integer, Dog>
# 1 楼答案
您可以这样做:
# 2 楼答案
看起来您可以信任您的
getSomeDogs()
方法始终返回Map<Integer, Dog>
,因此您可以执行以下操作:否则,您将执行以下操作:
# 3 楼答案
使用以下代码:
动物是一张地图
狗是一张地图
这只适用于JDK8
编辑:对于JDK6,使用以下代码: