原文: https://beginnersbook.com/2014/08/java-linkedlist-peek-peekfirst-and-peeklast-methods/

描述

public E peek():检索但不删除此列表的头部(第一个元素)。

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

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

示例

  1. import java.util.LinkedList;
  2. class LinkedListPeekDemo{
  3. public static void main(String[] args) {
  4. // Create a LinkedList of Strings
  5. LinkedList<String> list = new LinkedList<String>();
  6. // Add few Elements
  7. list.add("Element1");
  8. list.add("Element2");
  9. list.add("Element3");
  10. list.add("Element4");
  11. // Display LinkList elements
  12. System.out.println("LinkedList before: "+list);
  13. //peek()
  14. System.out.println(list.peek());
  15. //peekFirst()
  16. System.out.println(list.peekFirst());
  17. //peekLast()
  18. System.out.println(list.peekLast());
  19. // Should be same as peek methods does not remove
  20. System.out.println("LinkedList after: "+list);
  21. }
  22. }

输出:

  1. LinkedList before: [Element1, Element2, Element3, Element4]
  2. Element1
  3. Element1
  4. Element4
  5. LinkedList after: [Element1, Element2, Element3, Element4]