繁体   English   中英

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

[英]Iterator Infinite Loop - hasNext() and Next()

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

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;
    }

暂无
暂无

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

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