📜  Java中的 ArrayDeque peekLast() 方法

📅  最后修改于: 2022-05-13 01:54:41.649000             🧑  作者: Mango

Java中的 ArrayDeque peekLast() 方法

Java中的Java .util.ArrayDeque.peekLast() 方法用于检索或获取双端队列的最后一个元素。检索到的元素不会从队列中删除或移除,而是该方法只是返回它。如果双端队列中不存在任何元素或者它为空,则返回 Null。

句法:

Array_Deque.peekLast()

参数:该方法不带任何参数。

返回值:该方法返回 Deque 的最后一个元素。

下面的程序说明了Java.util.ArrayDeque.peekLast() 方法:
方案一:

// Java code to illustrate peekLast()
import java.util.*;
  
public class ArrayDequeDemo {
    public static void main(String args[])
    {
        // Creating an empty ArrayDeque
        Deque de_que = new ArrayDeque();
  
        // Use add() method to add elements into the Deque
        de_que.add("Welcome");
        de_que.add("To");
        de_que.add("Geeks");
        de_que.add("4");
        de_que.add("Geeks");
  
        // Displaying the ArrayDeque
        System.out.println("Initial ArrayDeque: " + de_que);
  
        // Displaying the last element
        System.out.println("The last element is: " + 
                                           de_que.peekLast());
  
        // Displaying the ArrayDeque after operation
        System.out.println("Final ArrayDeque: " + de_que);
    }
}
输出:
Initial ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
The last element is: Geeks
Final ArrayDeque: [Welcome, To, Geeks, 4, Geeks]

方案二:

// Java code to illustrate peekLast()
import java.util.*;
  
public class ArrayDequeDemo {
    public static void main(String args[])
    {
        // Creating an empty ArrayDeque
        Deque de_que = new ArrayDeque();
  
        // Use add() method to add elements into the Deque
        de_que.add(10);
        de_que.add(15);
        de_que.add(30);
        de_que.add(20);
        de_que.add(5);
  
        // Displaying the ArrayDeque
        System.out.println("Initial ArrayDeque: " + de_que);
  
        // Displaying the last element
        System.out.println("The last element is: " + 
                                           de_que.peekLast());
  
        // Displaying the ArrayDeque after operation
        System.out.println("Final ArrayDeque: " + de_que);
    }
}
输出:
Initial ArrayDeque: [10, 15, 30, 20, 5]
The last element is: 5
Final ArrayDeque: [10, 15, 30, 20, 5]

程序 3:对于一个空的双端队列:

// Java code to illustrate peekLast()
import java.util.*;
  
public class ArrayDequeDemo {
    public static void main(String args[])
    {
        // Creating an empty ArrayDeque
        ArrayDeque de_que = new ArrayDeque();
  
        // Displaying the ArrayDeque
        System.out.println("ArrayDeque: " + de_que);
  
        // Displaying the last element
        System.out.println("The last element is: " + de_que.peekLast());
    }
}
输出:
ArrayDeque: []
The last element is: null