java - 我的 peek() 方法不会返回队列的头部

标签 java queue

我制作了一个 QueueRunner 类。我试图找出在 poll() 或 Offer() 之后迭代到队列的头部,以使用 peek() 返回队列的头部。不过,我在返回队列的头部或前面时遇到了问题。

Public class Queue<T> {
private ArrayList<T> elements;

public Queue() {
    this.elements = new ArrayList<T>();
}

/**
* Offers an element to the end of the queue.
*
* @param    T   item
*/
public void offer(T element) {
    this.elements.add(element);
}

/**
* Peeks at, but does not remove, the element at the head of the queue.
*
* @return   T
*/
public T peek() {
    if(this.elements.size()==0) {
        return null;
    }
    else {
        return this.elements;
    // return this.elements.get(this.elements.size()-1);
    }
}

/**
* Polls an element from the head of the queue.
*
* @return   T
*/
public T poll() {
    return this.elements.remove(0);
}

最佳答案

this.elements.get(0) 将返回队列的头部/前端。由于队列是 FIFO 的,因此添加的第一个元素将是第一个进入的元素,因此是队列的头部。

关于java - 我的 peek() 方法不会返回队列的头部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58258916/

相关文章:

java - 将上下文添加到 Toast.MakeText

java - 从mysql中的相关表中选择值

java - 使用 Array-Java 实现队列

javascript - QUEUE and 'IF' 'ELSE' 'WHILE' statements from scratch and running functions

java - 提供 AppEngine 静态文件

java - 如何在没有 AttributeConverter 或 customUserType 的情况下使用 Hibernate 5.2.10 MySQL JSON 支持来映射到 Java 实体类?

laravel - 在 Laravel 中,如何控制 Job 是通过队列处理还是同步处理

java - 队列实现,入队方法不起作用

java - 创建操作作业的队列

Java:如何使用扫描仪检查文件是否包含整数或单词?