Java讨厌的迭代器赢得了';t返回链表中的元素
给定以下代码:Java讨厌的迭代器赢得了';t返回链表中的元素,java,exception,iterator,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; boole
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
}
public void insertIntoQueue(float-length、int-xElement、int-yElement、int-whichElement)
{
点-点=新点(像素、像素);
GeometricElement元素=null;
//一些代码
智能机器人;
布尔标志=假;
for(迭代器i=robotList.Iterator();i.hasNext();)
{
//Robot currentRobot=(Robot)i.next();
robotX=((Robot)(i)).getXlocation();
机器人=((机器人)(i)).getYlocation();
//更多代码,无关紧要
}
我有以下对象:机器人、几何加速度和点
我想在机器人链表上迭代,该链表定义为:
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>();
}
}
公共类地面{
//更多领域
私有LinkedList robotList;//用于存储机器人
公共场地(整行、整列)//ctor
{
//一些代码
this.robotList=新建LinkedList();
}
}
但是行:robotX=((Robot)(i)).getXlocation();
和robotY=((Robot)(i)).getYlocation();
引发异常dispatchUncaughtException
请注意,我不想从链表中删除元素,
我需要的是使用迭代器从当前元素获取字段
Robot robot = (Robot)iterator.next();
robotX = robot.getXlocation();
那怎么了
问候
Ron您试图将迭代器强制转换为机器人对象。这永远不会起作用,它不是机器人,而是迭代器
Robot robot = (Robot)iterator.next();
robotX = robot.getXlocation();
您注释掉的行实际上是正确的行,但删除强制类型除外:
Robot currentRobot = i.next();
因为您的迭代器是类型化的,所以您不需要强制转换,编译器确保您使用的是正确类型的对象
之后,您可以简单地:
robotX = currentRobot.getXlocation();
robotY = currentRobot.getYlocation();
没有丑陋的演员
顺便说一句,如果您不需要通过迭代器修改集合,您可以大大改进代码样式,使用“foreach”购买:
看起来你要将i转换为机器人,而它实际上是迭代器类型…也许你想转换i.next()?当我使用i.next()执行此操作时,“i”继续到下面的元素,并且不返回当前值,意思是“i”不会停留在当前元素上,它会移动到下一个元素,因此可能需要创建一个等于i.next()的临时Robot,以便可以使用它两次。我只是这样做了,但是,我对临时Robot所做的任何更改都不会更改linkedlist…如果您只是说Robot temp=i.next()呢那应该是指那个实际的变量,不是吗?我想你是用McCoy博士的语音输入的。哈哈