考虑下面的代码返回一个元素:恼人的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