Given the following code :
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
}
I have the following objects : Robot,GeometricElement and Dot .
I want to iterate on a Robot linked list which defined as:
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>();
}
}
but the line : robotX = ((Robot)(i)).getXlocation();
and robotY = ((Robot)(i)).getYlocation();
throws an exception of dispatchUncaughtException .
Please pay attention that I don’t want to remove elements from the linked list,
what I need is to get fields from a current element with the iterator.
So what’s wrong ?
Regards
Ron
Your commented out line is actually the correct line, except remove the cast:
Because your iterator is typed, you dont need the cast and the compiler ensures you’re working with the right kind of object.
After that, you can simply:
No ugly casts!
BTW, if you don’t need to modify the collection via the iterator, you can improve the code style considerably, buy using a “foreach”: