I am trying to implement a ring that remembers the last N elements. It adds element and changes the pointer correctly. The get() method must return the newest element added to the ring. I tried to find the logic in the get method with pen and paper and eventually, I managed to do it. However, when I run my code it does not seem so. Thanks for the help in advance.
[1][2][3][4][5] <- In the following example, get(0) has to return 5 and get(1) - 4
Iteration and print
[1][2][3][4][5]
Using the get method - get(0), get(1) ....
[1] [5] [4] [3] [2] - here [1] must be on the right side of [2]
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
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 null;
}
@Override
public int size()
{
return elements;
}
@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[ring.length + front -index];
}
else
{
return ring[front - index];
}
}
}
}