2011-08-26 85 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 

了解如何使用泛型和测试。不要在主函数中放置泛型参数,在那里是没用的。