-6

Queue12はインターフェースであり、QueueImp12はQueue12の実装です。だから私はQueueImp12をテストしようとしていますが、それをeclipseで実行(コンパイル)すると、出力がコンソールで終了します。ringBufferを正しく作成したと思います。私のテストがうまく見えたら、私の実装または日食に何か問題があるはずです。ありがとう

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.outsいくつかを置くかasserts、コードが実行されることを確認します(ここでは実行され、いくつかのひどいキャスト警告がありますが、実行されます)

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 に答える