简体   繁体   中英

Java annoying iterator won't return an element in a linked-list

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:

Robot currentRobot = i.next();           

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:

robotX = currentRobot.getXlocation();
robotY = currentRobot.getYlocation();

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":

for (Robot currentRobot : robotList) {
    robotX = currentRobot.getXlocation();
    robotY = currentRobot.getYlocation();
    // .. more code
}

You are trying to cast the iterator to a Robot object. That's never going to work, it's not a Robot, it's an iterator.

Robot robot = (Robot)iterator.next();
robotX = robot.getXlocation();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM