Java 集合 LinkedList poll(),pollFirst()和pollLast()方法

示例LinkedList类的poll()pollFirst()pollLast()方法的程序。

LinkedList.poll()

检索并删除此列表的头部(第一个元素)。

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

输出:

LinkedList before: [Element1, Element2, Element3, Element4]
Element removed: Element1
LinkedList after: [Element2, Element3, Element4]

LinkedList.pollFirst()

public E pollFirst():检索并删除此列表的第一个元素,如果此列表为空,则返回null

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

输出:

LinkedList before: [Element1, Element2, Element3, Element4]
Element removed: Element1
LinkedList after: [Element2, Element3, Element4]

LinkedList.pollLast()

public E pollLast():检索并删除此列表的最后一个元素,如果此列表为空,则返回null

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

输出:

LinkedList before: [Element1, Element2, Element3, Element4]
Element removed: Element4
LinkedList after: [Element1, Element2, Element3]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程