2011-08-24 77 views
0

我的代碼編譯但不起作用。我認爲我沒有說明對嗎?並可以有人向我解釋wrapIdx方法返回索引%容量。我真的不明白如何代碼包裝數組。當它到達數組索引的末尾時,容量將返回1,但不是數組從0開始索引?隊列RingBuffer實現隊列12。不起作用

這是我的代碼,我正在實現一個Queue12接口。在我得到這個工作後,我將能夠做一個測試類來檢查它是否工作?

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

} 

回答

1

所以這裏要注意的第一件事是,模運算%返回一個除法的餘數。任何模數本身都是0,因此當你達到隊列的最大容量時,它將返回0,這是你開始的索引。如果代碼在達到最終結果時返回1,那麼您有一個問題。

+0

是否與當前索引相同? – earbulan

+0

只有當前面和當前等於'0'時 – Woot4Moo