简体   繁体   English

Java烦人的迭代器不会在链表中返回元素

[英]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 . 我有以下对象:Robot,GeometricElement和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(); 但是行: robotX = ((Robot)(i)).getXlocation(); and robotY = ((Robot)(i)).getYlocation(); 和robotY = ((Robot)(i)).getYlocation(); throws an exception of dispatchUncaughtException . 抛出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": 顺便说一句,如果你不需要通过迭代器修改集合,你可以大大改善代码风格,使用“foreach”购买:

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

You are trying to cast the iterator to a Robot object. 您正在尝试将迭代器强制转换为Robot对象。 That's never going to work, it's not a Robot, it's an iterator. 那永远都行不通,不是机器人,而是迭代器。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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