2011-08-26 103 views
-6

Queue12是一個接口,QueueImp12是Queue12的一個實現。所以我試圖測試我的QueueImp12,但是當我在Eclipse中運行它(它編譯)我的輸出在控制檯中終止。我相信我正確地創建了ringBuffer。如果我的測試看起來很好,那麼我的執行或日食肯定有問題。謝謝Java的泛型問題

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

} 




public class P3test 
{ 
public static<T> void main(String[] args) 
{ 
    final Queue12<T> ringBuffer = new QueueImpl12<T>(); 
    T o = (T) new String("this"); 
    ringBuffer.enqueue(o); //add element to the back 
    ringBuffer.dequeue(); //remove/return element in the front 

} 
} 
+2

這不是有效的Java代碼。請你能解決它! –

+0

重新格式化您的代碼。我很明顯,它現在不會編譯。另外主要方法不是測試,有一天嘗試JUint(TDD太棒了)。 – fiction

+1

你爲什麼要將'String'轉換爲'T'?這沒有任何意義。 「T」從哪裏來? –

回答

2

你最近看到的'終止'是程序結束時的預期行爲。

把一些System.outsasserts驗證您的代碼運行(在這裏運行,一些可怕的投警告,但運行)

final Queue12<T> ringBuffer = new QueueImpl12<T>(); 
T o = (T) new String("this"); 
ringBuffer.enqueue(o); //add element to the back 
System.out.println(ringBuffer.peek());//this should print 'this' in the console\ 
//assertEquals('this', ringBuffer.peek()); 
ringBuffer.dequeue(); //remove/return element in the front 

瞭解如何使用泛型和測試。不要在主函數中放置泛型參數,在那裏是沒用的。