迭代程序无限循环-hasNext()和Next()



我正在尝试使用一个实现迭代器的迭代器。迭代器应该遍历一个哈希表。当我试图打印出哈希表中的元素时,我在某个地方得到了一个无限循环,并且同一个元素一直被打印,直到我终止程序。这是我的hasNext和next方法的代码(光标会跟踪哈希表中的下一个活动单元格,因为该表不会按顺序填充,而活动表示该单元格被占用):

public boolean hasNext()
    {
        boolean entry = false;
        //nextLoop:
        while(entry == false && cursor < table.length)
        {
            if(table[cursor] == null)
            {
                cursor++;
            }
            else
            {
                if(table[cursor].active == false)
                {
                    cursor++;
                }
                else
                {
                    entry = true;
                    //break nextLoop;
                }
            }
        }
        boolean entryStatus = (table[cursor] != null); // check to see if entry at cursor is null
        boolean activeStatus = table[cursor].active; // check to see if the cell is active (there is something inside the cell)
        return (entryStatus && activeStatus);
    }
    public Object next()
    {
        boolean entry = false;
        if(cursor >= table.length)
        {
            throw new NoSuchElementException(); //check - myexceptioN?
        }
        else
        {
            while(cursor < table.length && entry == false) 
            {
                if(table[cursor] != null) 
                {
                    if(table[cursor].active == true)
                    {
                        entry = true;
                    }
                    else
                    {
                        cursor++;
                    }
                }
                else if(table[cursor] == null)
                {
                    cursor++;
                }
            }

        }
        return table[cursor].element;
    }

如果您有一个元素,那么next()方法应该返回该光标下的元素(按原样),然后更新光标(不按原样)。因此,您的代码总是停留在同一个元素上,因为hasNext将使用相同的光标位置进行调用。

在下一个方法中获得值后,需要将光标移动到下一个位置。

正如用户Ryan J在评论中所说,您应该同时使用next()和hasNext()方法。并且您需要在调用next之后增加光标。

    public Object next() {
        if (cursor >= table.length  || table[cursor].active == true 
             || table[cursor] == null) {
            throw new NoSuchElementException(); 
        }
        return table[cursor++].element;
    }

最新更新