ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Java - `LinkedList poll()`,`pollFirst()`和`pollLast()`方法 > 原文: [https://beginnersbook.com/2014/08/java-linkedlist-poll-pollfirst-and-polllast-methods/](https://beginnersbook.com/2014/08/java-linkedlist-poll-pollfirst-and-polllast-methods/) #### 描述 示例`LinkedList`类的`poll()`,`pollFirst()`和`pollLast()`方法的程序。 #### `LinkedList.poll()` 检索并删除此列表的头部(第一个元素)。 ```java import java.util.LinkedList; class LinkedListPollMethod{ public static void main(String[] args) { // Create a LinkedList of Strings LinkedList<String> list = new LinkedList<String>(); // Add few Elements list.add("Element1"); list.add("Element2"); list.add("Element3"); list.add("Element4"); // Display LinkList elements System.out.println("LinkedList before: "+list); /* poll(): Retrieves and removes the head (first element) * of this list. */ System.out.println("Element removed: "+list.poll()); // Displaying list elements after poll() operation System.out.println("LinkedList after: "+list); } } ``` **输出:** ```java LinkedList before: [Element1, Element2, Element3, Element4] Element removed: Element1 LinkedList after: [Element2, Element3, Element4] ``` #### `LinkedList.pollFirst()` `public E pollFirst()`:检索并删除此列表的第一个元素,如果此列表为空,则返回`null`。 ```java import java.util.LinkedList; class LinkedListPollFirstDemo{ public static void main(String[] args) { // Create a LinkedList of Strings LinkedList<String> list = new LinkedList<String>(); // Add few Elements list.add("Element1"); list.add("Element2"); list.add("Element3"); list.add("Element4"); // Display LinkList elements System.out.println("LinkedList before: "+list); /* pollFirst(): Retrieves and removes the first element * of this list, or returns null if this list is empty. */ System.out.println("Element removed: "+list.pollFirst()); // Display list after calling pollFirst() method System.out.println("LinkedList after: "+list); } } ``` **输出:** ```java LinkedList before: [Element1, Element2, Element3, Element4] Element removed: Element1 LinkedList after: [Element2, Element3, Element4] ``` #### `LinkedList.pollLast()` `public E pollLast()`:检索并删除此列表的最后一个元素,如果此列表为空,则返回`null`。 ```java import java.util.LinkedList; class LinkedListPollLastDemo{ public static void main(String[] args) { // Create a LinkedList of Strings LinkedList<String> list = new LinkedList<String>(); // Add few Elements list.add("Element1"); list.add("Element2"); list.add("Element3"); list.add("Element4"); // Display LinkList elements System.out.println("LinkedList before: "+list); /* pollFirst(): Retrieves and removes the first element * of this list, or returns null if this list is empty. */ System.out.println("Element removed: "+list.pollLast()); // Display after calling pollLast() method System.out.println("LinkedList after: "+list); } } ``` **输出:** ```java LinkedList before: [Element1, Element2, Element3, Element4] Element removed: Element4 LinkedList after: [Element1, Element2, Element3] ```