【发布时间】:2011-11-04 09:56:35
【问题描述】:
Queue12 是一个接口,QueueImp12 是Queue12 的一个实现。所以我正在尝试测试我的 QueueImp12 但是当我在 Eclipse 中运行它(它编译)时,我的输出在控制台中终止。我相信我正确地创建了 ringBuffer。如果我的测试看起来不错,那么我的实现或 Eclipse 一定有问题。谢谢
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
}
}
【问题讨论】:
-
这不是有效的 Java 代码。请你解决它!
-
重新格式化您的代码。我很明显它现在不会编译。 main 方法也不是测试,改天试试 JUint(TDD 太棒了)。
-
为什么要将
String转换为T?这没有任何意义。T来自哪里? -
如果它编译,泛型部分应该没问题。您看到的具体问题是什么?它应该输出什么吗?
-
我还有 2 个其他类,公共接口 Queue12
{..} 和公共类 QueueImpl12 实现 Queue12 {..} 我想通过 main 以某种方式对其进行测试,但没有不确定我可以在 enqueue() 中放入什么来测试它(现在开始学习 Junit/TDD)。我不明白什么类型 它只是对象类型?由于您不能将字符串直接放入队列中,因此我认为制作 T 类型的字符串会起作用。
标签: java eclipse generics queue circular-buffer