簡體   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