-6

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

}
 }
4

1 回答 1

2

您最近看到的“终止”是程序完成时的预期行为。

放一些System.outsorasserts来验证你的代码是否运行(在这里它运行,带有一些可怕的强制转换警告,但运行)

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

学习如何使用泛型和测试。并且不要将泛型参数放在主函数中,在那里是没用的。

于 2011-08-26T11:05:40.150 回答