简体   繁体   English

使用HashMap进行Set的迭代器不会产生值/键吗?

[英]Iterator for Set using HashMap won't produce the value / key?

Given the following code : 给出以下代码:

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 

}

class Coordinate 类坐标

package model; 包装型号;

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;

    }

}

And a method of Game class : 以及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 doesn't have an iterator , so I used Set in order to get the elements of the hashmap. HashMap没有迭代器,因此我使用Set来获取哈希图的元素。 My problem started when I wanted to iterate on the values of the HashMap , but since that's not possible , I tried with Set , but Set returns an Object and not the Coordinate object itself . 当我想对HashMap的值进行迭代时,我的问题就开始了,但是由于不可能,我尝试了Set ,但是Set返回了一个Object而不是Coordinate对象本身。 Is there a way to get it ? 有办法吗?

Regards,Ron 问候罗恩

The problem is that you're using the raw types for the set and iterator - you should use the generic types: 问题是您正在使用原始类型的集合和迭代器-您应该使用通用类型:

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

Or: 要么:

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

On the other hand, if you really do just want to iterate over the values of the map: 在另一方面,如果你真的只是想遍历地图的价值:

Iterator<Coordinate> valueIterator = this.m_myHashMap.values().iterator();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM