有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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>


共 (3) 个答案

  1. # 1 楼答案

    您可以这样做:

        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());        
    
        }
    
  2. # 2 楼答案

    看起来您可以信任您的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;
    }
    
  3. # 3 楼答案

    使用以下代码:

    animals.forEach((Integer integer, Animal animal) -> dogs.put(
                            integer, (Dog) animal));
    

    动物是一张地图
    狗是一张地图
    这只适用于JDK8

    编辑:对于JDK6,使用以下代码:

    animals.forEach(new BiConsumer<Integer, Animal>() {
        public void accept(Integer integer, Animal animal) {
            dogs.put(integer, animal); // You may have to make dogs final
        }
    }