0

给定以下代码:

public class Game {



    private Map<String,Coordinate> m_myHashMap;
... // more code 
}

public Game(Display display,int level) 
{
        this.m_myHashMap = new HashMap<String,Coordinate>();
... // more code 

}

类坐标

封装模型;

public class Coordinate {

    private int xCoordinate;
    private int yCoordinate;
    private int sign;

    public Coordinate(int x,int y)
    {
        this.xCoordinate = x;
        this.yCoordinate = y;
        this.sign = 0;
    }

    public int getXCoordinate()
    {
        return this.xCoordinate;
    }

    public int getYCoordinate()
    {
        return this.yCoordinate;
    }

    public void setSign(int number)
    {
        this.sign = number;
    }

    public int getSign()
    {
        return this.sign;
    }

    public void setXcoordinate(int newX)
    {
        this.xCoordinate = newX;

    }

    public void setYcoordinate(int newY)
    {
        this.yCoordinate = newY;

    }

}

还有一个 Game 类的方法:

private void placeTreasuresInMaze(PaintEvent e)
{
    // e.gc.drawPolygon(new int[] { 25+x,5+y,45+x,45+y,5+x,45+y });
    int numberOfTreasures = this.m_numberOfPlayers * 3;  // calculate number of treasures 
    Set set = this.m_myHashMap.entrySet();
    Iterator iterator = set.iterator();     

    while (numberOfTreasures > 0 && iterator.hasNext())
    {
        numberOfTreasures--;
        // need to add more code here 

    }
}

HashMap没有迭代器,所以我使用 Set 来获取哈希图的元素。当我想迭代 的值时,我的问题就开始了HashMap,但由于那是不可能的,所以我尝试了Set,但Set返回的是 anObject而不是Coordinate对象本身。有没有办法得到它?

问候,罗恩

4

1 回答 1

4

问题是您使用集合和迭代器的原始类型 - 您应该使用泛型类型:

Iterator<Map.Entry<String, Coordinate>> iterator = m_myHashMap.entrySet()
                                                              .iterator();

或者:

Set<Map.Entry<String, Coordinate>> set = this.m_myHashMap.entrySet();
Iterator<Map.Entry<String, Coordinate>> iterator = set.iterator();     

另一方面,如果您真的只想遍历地图的值:

Iterator<Coordinate> valueIterator = this.m_myHashMap.values().iterator();
于 2012-01-28T13:49:07.733 回答