迭代一张地图

时间:2014-12-13 01:33:54

标签: java map foreach hashmap

我试图在Java中迭代一张地图......它看起来对我好,但事实并非如此。我得到的错误是

Required: java.util.Map.Entry <java.lang.Integer, com.model.Horse>
Found: java.lang.Object

这是我的代码

public Map loadHorses() {

    Map<Integer, Horse> horses = new HashMap<Integer, Horse>();

    // static set of horses, no reason not to hardcode them
    horses.put(1, new Horse("That Darn Gray Cat", 5, false));
    horses.put(2, new Horse("Fort Utopia", 10, false));
    horses.put(3, new Horse("Count Sheep", 9, false));
    horses.put(4, new Horse("Ms Traitour", 4, false));
    horses.put(5, new Horse("Real Princess", 3, false));
    horses.put(6, new Horse("Pa Kettle", 5, false));
    horses.put(7, new Horse("Gin Stinger", 6, false));

    return horses;
}

public void displayHorses(Map horses) {
    StringBuilder sb = new StringBuilder();
    sb.append("Horses:\n");

    for(Map.Entry<Integer, Horse> horse : horses.entrySet()){
        sb.append(horse.getKey() + ", " + horse.getValue().getName() + ", " + horse.getValue().getOdds() + ", " + horse.getValue().isWon());
    }
}

我做错了什么?

0 个答案:

没有答案