考慮下面的代碼返回一個元素:惱人的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
異常。
請注意,我不想從鏈表中刪除元素, 我需要的是從迭代器中獲取當前元素的字段。
那麼,怎麼了?
問候 羅恩
你看上去鑄造我當它實際上是類型Iterator ......也許你想要投射i.next()而不是? –
AndyG
當我用i.next()做到這一點時,「i」進入下列元素,並且不返回當前值,這意味着「i」不會保留在當前元素上,而是移動到下一個元素 – ron
So也許你想創建一個等於i.next()的臨時機器人,以便你可以使用它兩次。 – AndyG