2011-12-12 67 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