给出以下代码:
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的元素。
当我想要迭代HashMap
的值时,我的问题就开始了,但由于那是不可能的,我尝试使用Set
,但是Set
会返回Object
而不是Coordinate
对象本身。
有办法搞定吗?
的问候,罗恩
答案 0 :(得分:4)
问题是您使用了set和iterator的原始类型 - 您应该使用泛型类型:
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();