[英]Iterator for Set using HashMap won't produce the value / key?
給出以下代碼:
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
返回了一個Object
而不是Coordinate
對象本身。 有辦法嗎?
問候羅恩
問題是您正在使用原始類型的集合和迭代器-您應該使用通用類型:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.