如何在Map中找到值的类型?

时间:2015-05-01 01:58:34

标签: java dictionary types

如果有这样的话:

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>

2 个答案:

答案 0 :(得分:1)

看起来您可以信任getSomeDogs()方法始终返回Map<Integer, Dog>,所以您可以这样做:

@SuppressWarnings("unchecked")
public Map<Integer, Dog> specificallyGetSomeDogs()
{
    Map<Integer, Dog> result = new HashMap<Integer, Dog>();
    Map map = getSomeDogs();
    result.putAll(map);
    return result;
}

否则,你会这样做:

public Map<Integer, Dog> specificallyGetSomeDogs()
{
    Map<Integer, Dog> result = new HashMap<Integer, Dog>();
    Map<Integer, Animal> map = getSomeDogs();
    for (Map.Entry<Integer, Animal> integerAnimalEntry : map.entrySet()) {
        result.put(integerAnimalEntry.getKey(), (Dog) integerAnimalEntry.getValue());
    }
    return result;
}

答案 1 :(得分:0)

你可以这样做:

    Map<Integer, Dog> specificDogs= new HashMap<Integer, Dog>();

    Iterator it = dogs.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();          

        specificDogs.put((Integer)pair.getKey(), (Dog)pair.getValue());        

    }
相关问题