[英]Implementing Iterator.remove()
我已經實現了通用的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()
{
}
}
}
Javadoc對此很清楚:
您可以選擇不實現該方法,在這種情況下,您只需拋出UnsupportedOperationException
如果實現它,則必須從基礎集合中刪除迭代器當前選擇的元素。 在以下沒有選擇任何元素的情況下,將引發IllegalStateException:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.