Ich habe ein generisches CircularArrayRing implementiert und arbeite daran, einen Iterator dafür zu implementieren. Ich frage mich, wie funktioniert die remove() Methode eines Iterators? Muss der Ring tatsächlich geändert werden oder eine Kopie davon zurückgegeben werden, wenn das angegebene Element entfernt wurde?Implementierung von Iterator.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()
{
}
}
}
remove() sollte das Element zurückgeben, das in der Sammlung war, und die vorhandene Sammlung ändern. remove() gibt die Sammlung überhaupt nicht zurück. – MeBigFatGuy
Der Rückgabetyp von Entfernen ist ungültig, daher gibt diese Methode nichts zurück – toongeorges
Sie können den Quellcode der vorhandenen Implementierung überprüfen. –