Queue 中 element() 和 peek() 的区别

版权声明:转载请注名出处 https://blog.csdn.net/meism5/article/details/89884497

在 Queue 中 element() 和 peek()有什么区别?

Queue 中 element() 和 peek()都是用来返回队列的头元素,不删除。

在队列元素为空的情况下,element() 方法会抛出NoSuchElementException异常,peek() 方法只会返回 null。

JDK1.8

/**
 * Retrieves, but does not remove, the head of this queue.  This method
 * differs from {@link #peek peek} 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 element();

/**
 * Retrieves, but does not remove, 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 peek();

猜你喜欢

转载自blog.csdn.net/meism5/article/details/89884497