Queue的remove()和poll()方法有什么區別?


  • Queue 中 remove() 和 poll() 都是用來從隊列頭部刪除一個元素。
  • 在隊列元素為空的情況下,remove() 方法會拋出NoSuchElementException異常,poll() 方法只會返回 null 。

 

JDK1.8 中的源碼解釋

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

 

  

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


免責聲明!

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



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