2011-12-12 68 views
1

考虑下面的代码返回一个元素:恼人的Java迭代器将无法在链表

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 
    } 

我有以下对象:机器人,GeometricElement和斑点。

我想重复其定义为机器人链表:

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异常。

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

那么,怎么了?

问候 罗恩

+0

你看上去铸造我当它实际上是类型Iterator ......也许你想要投射i.next()而不是? – AndyG

+0

当我用i.next()做到这一点时,“i”进入下列元素,并且不返回当前值,这意味着“i”不会保留在当前元素上,而是移动到下一个元素 – ron

+1

So也许你想创建一个等于i.next()的临时机器人,以便你可以使用它两次。 – AndyG

回答

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

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

Robot robot = (Robot)iterator.next(); 
robotX = robot.getXlocation(); 
+1

我假设你在Dr. McCoy的声音中输入那个。 –

+0

哈哈[我是医生,不是瓦工!](http://en.wikipedia.org/wiki/Leonard_McCoy#.22I.27m_a_doctor.2C_not_a.28n.29 ... 22) – Bohemian