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();

 

  

來一道刷了進BAT的面試題?


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM