0

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];
}

}
sbridges
  • 24,960
  • 4
  • 64
  • 71
earbulan
  • 37
  • 4

1 Answers1

1

So the first thing to note here is that the modulo operator % returns the remainder of a division. Any number modulo itself is 0, therefore when you hit the maximum capacity of the queue it will return 0, which is the index you will start at. If the code is returning 1 when it hits the end, you have an off by one issue.

Woot4Moo
  • 23,987
  • 16
  • 94
  • 151