Queue的element()和peek()方法有什么区别

参考答案

Queue的element()和peek()方法的区别:

  • Queue 中 element() 和 peek() 都是用来返回队列的头元素,不删除;
  • 在队列元素为空的情况下,element() 方法会抛出NoSuchElementException异常,peek() 方法只会返回 null。

JDK1.8 中源码解释:

  1. /**
  2. * Retrieves, but does not remove, the head of this queue. This method
  3. * differs from {@link #peek peek} only in that it throws an exception
  4. * if this queue is empty.
  5. *
  6. * @return the head of this queue
  7. * @throws NoSuchElementException if this queue is empty
  8. */
  9. E element();
  10. /**
  11. * Retrieves, but does not remove, the head of this queue,
  12. * or returns {@code null} if this queue is empty.
  13. *
  14. * @return the head of this queue, or {@code null} if this queue is empty
  15. */
  16. E peek();

 

以上,是Java面试题【Queue的element()和peek()方法有什么区别】的参考答案。

输出,是最好的学习方法

欢迎在评论区留下你的问题、笔记或知识点补充~

—end—

0 条回复 A文章作者 M管理员
欢迎您,新朋友,感谢参与互动!
    暂无讨论,说说你的看法吧