在Java中实现remove()Iterator方法

时间:2017-10-25 01:44:37

标签: java generics linked-list iterator iteration

所以我正在使用通用的LinkedList,我需要能够使用迭代器来删除它的后半部分。但是,我似乎无法让它发挥作用。这是迭代器调用:

<activity
    android:name=".algebra_activity"
    android:theme="@style/AppTheme.NoActionBar">

这是我的迭代器方法:

    Iterator<String> itr = seq.iterator();
    for (int i = 0; i < N / 2; i++)
    {
        itr.next();
    }

    for (int i = 0; i < N / 2; i++)
    {
        itr.next();
        itr.remove();
    }

它在第二个for循环下的itr.next()调用上给出NoSuchElementException。我最好的猜测是它可能与我确定前一个节点位置的方式有关;类DOES有一个getPrevious()方法:

    boolean canRemove = false;
    int previousLoc = -1;
    Node<T> current = head;

    @Override
    public boolean hasNext()
    {
        return current != null;
    }

    @Override
    public T next()
    {
        if (hasNext())
        {
            T data = current.getData();
            current = current.getLink();
            previousLoc++;
            canRemove = true;
            return data;
        }
        throw new NoSuchElementException();
    }

    public void remove()
    {
        if (!canRemove)
        {
            throw new IllegalStateException();
        }

        SortedLinkedList.this.remove(previousLoc);
        canRemove = false;

    }

一个getPosition方法:

private Node<T> getPrevious(T entry)
{
    Node<T> previous = null;
    Node<T> traverse = head;
    while (traverse != null)
    {
        //if(entry.compareTo((T) traverse.getData()) > 0)
        if (traverse.getData().compareTo(entry) < 0)
        {
            previous = traverse;
            traverse = traverse.getLink();
        }
        else
        {
            return previous;
        }
    }
    return previous;
}

但是,如果我尝试类似

的话
public int getPosition(T anEntry)
{
    Node<T> traverse = head;
    for (int i = 0; i < manyNodes; i++, traverse = traverse.getLink())
    {
        if(anEntry.compareTo(traverse.getData()) == 0)
        {
            return i;
        }
    }
    throw new IllegalArgumentException("Element not in list");
}

我得到&#34; solution.Node无法转换为java.lang.Comparable&#34;

即使类标题确实扩展了它:

SortedLinkedList.this.remove(getPosition((T) getPrevious((T) current)));

编辑:这是删除方法:

public class SortedLinkedList<T extends Comparable<? super T>> implements Iterable<T>

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

public void remove()
{
    if (!canRemove)
    {
        throw new IllegalStateException();
    }
    SortedLinkedList.this.remove(previousLoc--);
    canRemove = false;
}

在循环中,next()的调用会增加previousLoc,而remove()方法会从列表中删除该项,但它并未更改previousLoc的值。因此,previousLoc保持递增,而所有元素都将被移除。

要查看此内容,您应在previousLocnext()期间打印remove() ...