给出以下代码:
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
返回一个对象
,而不是坐标
对象本身。
有办法获取吗?
问候,罗恩
最佳答案
问题是您正在使用集合和迭代器的原始类型 - 您应该使用泛型类型:
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();
另一方面,如果您确实确实只想迭代 map 的值:
Iterator<Coordinate> valueIterator = this.m_myHashMap.values().iterator();
关于java - 使用 HashMap 的 Set 迭代器不会产生值/键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9045706/