Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中实现队列?_Java_Queue - Fatal编程技术网

如何在java中实现队列?

如何在java中实现队列?,java,queue,Java,Queue,我想做和我在堆栈代码中做的一样的事情 我如何更改它以使其成为队列?我不想为此使用stack或LinkedList public StackAsArray(){ this(new DynamicArray()); } public boolean isEmpty() { } public void push(Object o) { } public Object pop() { } } 您只需将push和pop

我想做和我在堆栈代码中做的一样的事情 我如何更改它以使其成为队列?我不想为此使用stack或LinkedList

    public StackAsArray(){
        this(new DynamicArray());
    }
    public boolean isEmpty() {

    }
    public void push(Object o) {

    }
    public Object pop() {

    }
}

您只需将
push
pop
方法替换为
enqueue
dequeue
方法

enqueue
将元素添加到数组的末尾,而
dequeue
将从数组的开头删除元素

public class QueueAsArray implements Queue {
    ...

    public void enqueue(Object o) {
        arr.set(numOfElements, o);
        numOfElements++;
    }

    public Object dequeue() {
        if(isEmpty()) {  // an empty check is a MUST
            return null; 
        }

        numOfElements = numOfElements - 1;
        Object res = arr.get(0);
        arr.set(0, null); // not 100% sure this works, but since this is a homework question, its upto you to figure out. The logic is to remove the 0th element.
        return res;
    }
}

通过思考你的家庭作业和尝试。而不是放弃一些代码和要求。