My code compiles but doesn't work. I think i didn't typecast right? and can someone explain to me wrapIdx method return index % capacity. i don't really understand how that code wraps the array. when it reaches the end of the array index % capacity will return 1, but doesn't an array start at 0 index?
Here's my code, i'm implementing a Queue12 interface. After i get this to work, will i be able to make a test class to check if it works?
import java.util.NoSuchElementException;
public class QueueImpl12<T> implements Queue12<T>
{
private int _size, _backIdx, _frontIdx;
private static final int _defaultCapacity = 128;
private T[] _ringBuffer;
public QueueImpl12(int capacity)
{
_ringBuffer = (T[]) new Object[capacity];
clear();
}
public QueueImpl12()
{
_ringBuffer = (T[]) new Object[_defaultCapacity];
clear();
}
private int wrapIdx(int index)
{
return index % capacity();
}
public void clear()
{
_backIdx = 0;
_frontIdx = 0;
_size = 0;
}
@Override
public int capacity()
{
// TODO Auto-generated method stub
return _ringBuffer.length;
}
@Override
public int size()
{
// TODO Auto-generated method stub
return _size;
}
@Override
public boolean enqueue(T o)
{
//add o to back of queue
if(_ringBuffer.length == _size)
{
return false;
}
_ringBuffer[_backIdx] = o;
_backIdx = wrapIdx(_backIdx + 1 );
_size++;
return true;
}
@Override
public T dequeue()
{
if(_size == 0) //empty list
{
throw new NoSuchElementException();
}
T tempObj = _ringBuffer[_frontIdx]; //store frontIdx object
_ringBuffer[_frontIdx] = null;
_frontIdx++;
_size--;
return tempObj;
}
@Override
public T peek()
{
return _ringBuffer[_frontIdx];
}
}