实现Iterator.remove()

时间:2017-03-08 17:49:17

标签: java iterator

我已经实现了一个通用的CircularArrayRing,我正在为它实现一个迭代器。我想知道迭代器的remove()方法是如何工作的。是否必须实际修改环或返回指定元素的副本?

import java.util.AbstractCollection;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class CircularArrayRing<E> extends AbstractCollection<E> implements Ring<E>
{

    private int elements;
    private int front;
    private E[] ring;

@SuppressWarnings("unchecked")
public CircularArrayRing()
{
    ring = (E[]) new Object[10];
    front = 0;
}

@SuppressWarnings("unchecked")
public CircularArrayRing(int size)
{
    ring = (E[]) new Object[size];
    front = 0;
}

@Override
public boolean add(E e) 
{

    ring[front] = e;
    front++;

    if(front == ring.length)
    {
        front = 0;
    }

    if(elements < ring.length)
    {
        elements++;
    }

    return false;
}

@Override
public Iterator<E> iterator() 
{   
    return new RingIterator();
}

@Override
public int size() 
{
    return elements;
}

//returns the element at the specified position
//the last added element has index 0, the second most recent has index 1 etc
@Override
public E get(int index) throws IndexOutOfBoundsException 
{
    if(index > elements - 1 || index > ring.length - 1) 
    {   
        throw new IndexOutOfBoundsException();
    }
    else
    {   
        if (index < front) 
        {
            return ring[front - 1 - index];
        }
        else 
        {
            return ring[ring.length + front - 1 - index];
        }
    }


  }


@SuppressWarnings("rawtypes")
private class RingIterator implements Iterator<E>
{
    private int currentIndex = 0;


    // returns the next element in the iterator
    @SuppressWarnings("unchecked")
    @Override
    public E next() 
    {
        if(currentIndex > ring.length - 1)
        {
            throw new NoSuchElementException();
        }


        if (currentIndex < front)
        {   
            return (E) ring[front - 1 - currentIndex++];
        }
        else
        {
            return (E) ring[ring.length + front - 1 - currentIndex++];


        }

    }   


    //checks if there is another element 
    @Override
    public boolean hasNext() 
    {
        if(currentIndex < elements )
        {
            return true;
        }
        else
        {   
            return false;
        }

    }



    public void remove()
    {


    }

}   

}

1 个答案:

答案 0 :(得分:0)

Javadoc对此很清楚:

您可以选择不实现该方法,在这种情况下,您只需抛出UnsupportedOperationException

如果实现它,则必须从基础集合中删除迭代器当前选择的元素。在以下没有选择元素的情况下,抛出IllegalStateException:

  • 迭代器上的next()方法尚未被调用
  • 对于相同的选定元素(在第一次调用后已删除),多次调用remove()方法