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

}
4

1 回答 1

1

所以这里首先要注意的是模运算符%返回除法的余数。任何模数本身都是 0,因此当您达到队列的最大容量时,它将返回 0,这是您将开始的索引。如果代码在结束时返回 1,则您遇到了一个问题。

于 2011-08-24T14:11:42.320 回答