Java恼人的迭代器不会返回链表中的元素

时间:2011-12-12 02:25:24

标签: java exception iterator

给出以下代码:

public void insertIntoQueue(float length,int xElement,int yElement,int whichElement)
    {
        Dot dot = new Dot(xElement,yElement);
        GeometricElement element = null;

        // some code 

        int robotX,robotY;
        boolean flag = false;
        for (Iterator<Robot> i = robotList.iterator(); i.hasNext();)
        {

            // Robot currentRobot = (Robot) i.next();           

             robotX = ((Robot)(i)).getXlocation();
             robotY = ((Robot)(i)).getYlocation();

        // more code , irrelevant 
    }

我有以下对象:Robot,GeometricElement和Dot。

我想迭代一个定义为:

的Robot链表
public class Ground {

    // more fields 

    private LinkedList <Robot> robotList;  // used for storing the robots 
    public Ground(int row,int col)   // ctor 
{
            // some code 

    this.robotList = new LinkedList<Robot>();
}
}

但行:robotX = ((Robot)(i)).getXlocation(); 和robotY = ((Robot)(i)).getYlocation(); 抛出dispatchUncaughtException的例外。

请注意我不想删除链表中的元素, 我需要的是使用迭代器从当前元素中获取字段。

那有什么不对?

此致 罗恩

2 个答案:

答案 0 :(得分:2)

您注释掉的行实际上是正确的行,除了删除演员:

Robot currentRobot = i.next();           

因为你的迭代器被输入了,你不需要强制转换,编译器会确保你使用正确的对象。

之后,你可以简单地说:

robotX = currentRobot.getXlocation();
robotY = currentRobot.getYlocation();

没有丑陋的演员!


顺便说一句,如果你不需要通过迭代器修改集合,你可以大大改善代码风格,使用“foreach”购买:

for (Robot currentRobot : robotList) {
    robotX = currentRobot.getXlocation();
    robotY = currentRobot.getYlocation();
    // .. more code
}

答案 1 :(得分:1)

您正在尝试将迭代器强制转换为Robot对象。这永远不会起作用,它不是机器人,它是一个迭代器。

Robot robot = (Robot)iterator.next();
robotX = robot.getXlocation();
相关问题