如何使用 .next() 遍历对象映射?

How to iterate through a map of objects using .next()?

我在我的位置 class 中实现了 Iterable,它存储了一个对象地图,以允许遍历地图中的每个对象。

但是当我测试这段代码时,只加载了第一个位置,即"Tiberius" 当我输入 a, move 命令时。

有人知道为什么地图中的下一个位置没有在此实现中加载吗?

这是添加了位置的地图和迭代器方法:

private Map<Location, Integer> children = new HashMap<Location, Integer>();



        @Override
        public Iterator<Location> iterator() {
             return children.keySet().iterator();
        }

在开始位置调用 .next() 的主要 class:

public class Main {

    public static void main(String[] args)  {

        //Boolean to signify game state 
        boolean gameNotOver = true;

        Location nextLocation = new Location();
        Location startNode = new Location();

        Iterator<Location> nodeIterator = startNode.iterator();


        GameMap playerMap = new GameMap();
        playerMap.getStartNode();

        //get the first location in the map
        startNode = playerMap.getStartNode();

        //main game loop
        while (gameNotOver) {

            Main mainObj = new Main();

            //Take in user commands here
            //and parse commands
            String input = Input.getInput();
            if (input.equals("description")) {
                System.out.println("Description: " );
            } else if (input.equals("move")) {
                System.out.println("Moving.. " );
                //call the next location in the map
                startNode.next();
                System.out.println(startNode.toString());
            //Invalid input check
            else {
                System.out.println("Invalid command, try again!");
            }

        }

        //Game over 
        System.out.println("Game Over!");
        System.exit(0);
    }

}

您正在使用

startNode.next();
System.out.println(startNode.toString());

但您永远不会更改 startNode。难怪为什么总是打印相同的位置。将此代码更改为

startNode = startNode.next();
System.out.println(startNode.toString());

它应该可以工作。