程序员社区

(Java集合面试题)poll()方法和remove()方法区别?

Queue队列中,poll() 和 remove() 都是从队列中取出一个元素,在队列元素为空的情况下,remove() 方法会抛出异常,poll() 方法只会返回 null 。

看一下源码的解释吧:

/**
     * Retrieves and removes the head of this queue.  This method differs
     * from {@link #poll poll} only in that it throws an exception if this
     * queue is empty.
     *
     * @return the head of this queue
     * @throws NoSuchElementException if this queue is empty
     */
    E remove();

        /**
     * Retrieves and removes the head of this queue,
     * or returns {@code null} if this queue is empty.
     *
     * @return the head of this queue, or {@code null} if this queue is empty
     */
    E poll();

Java面试题

赞(0) 打赏
未经允许不得转载:IDEA激活码 » (Java集合面试题)poll()方法和remove()方法区别?

一个分享Java & Python知识的社区