因此,对于我的cs类,我们必须使用泛型和数组实现java Queue方法。我在搞清楚如何让测试人员类测试这些方法时遇到了一些麻烦。我很抱歉基本的问题,但我的CS老师不是很好,并告诉我们如何实际编码。
import java.util.NoSuchElementException;
import java.util.Queue;
public class SimpleQueue<E> implements Queue<E> {
private E[] array;
int Heads = 0;
int Tails = 0;
//Queue constructor
public SimpleQueue(int size)
{
//create an array
array = (E[])new Object[size];
int Heads = 0;
int Tails = 0;
}
//this removes
public E remove(){
if(isEmpty()){
return null;
}
else if(Heads == Tails){
E temp = array[Heads];
array[Heads] = null;
Heads--;
return temp;
}
else if(Heads != Tails && Heads < Tails){
return array[Heads++];
}
return null;
}
public void clear(){
Heads = 0;
Tails = 0;
array[0] = null;
}
//checks if the array is empty by checking if the first position is set to null
public boolean isEmpty(){
if(Heads == 0 && Tails == 0 && array[0] == null){
return true;
}
else{
return false;
}
}
public int size(){
if(isEmpty()){
return 0;
}
else if(Heads == Tails){
return 1;
}
else if(Heads < Tails){
return Tails - Heads + 1;
}
else if(Heads > Tails){
return array.length - Heads - Tails + 1;
}
return -1;//-1 indicate error
}
public Object[] toArray(){
Object[] tempArray = new Object[array.length];
if(isEmpty()){
return tempArray;
}
else if(Heads <= Tails){
for(int i = Heads; i <= Tails; i++){
tempArray[i] = array[i];
}
}
else if(Heads > Tails){
for(int i = Heads; i <= array.length; i++){
tempArray[i] = array[i];
}
for(int i = 0; i <= Tails; i++){
tempArray[i] = array[i];
}
}
return tempArray;
}
public E element(){
if(isEmpty()){
throw new NoSuchElementException();
}
else{
return array[Heads];
}
}
public E peek(){
if(isEmpty()){
return null;
}
else{
return array[Heads];
}
}
我试图开始一个新的队列,这就是我认为你应该这样做的方式 公共类SimpleQueueTester扩展了SimpleQueue {
public SimpleQueueTester(int size) {
super(size);
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public void main(String[] args) {
new SimpleQueue(5);
}
}