📜  Java中的集合 asLifoQueue() 方法和示例

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

Java中的集合 asLifoQueue() 方法和示例

Java.util.Collections类的asLifoQueue()方法用于将 Deque 的视图作为后进先出 (Lifo) 队列返回。方法 add 映射到 push,remove 映射到 pop 等等。当您想使用需要队列但需要 Lifo 排序的方法时,此视图可能很有用。
此方法返回的队列上的每个方法调用都会导致后备双端队列上的方法调用只有一个,但有一个例外。 addAll 方法被实现为支持双端队列上的一系列 addFirst 调用。
句法:

public static Queue asLifoQueue(Deque deque)

参数:该方法以deque作为参数,将其转换为 LifoQueue。
返回值:此方法从双端队列返回LifoQueue
下面是说明asLifoQueue()方法的示例
示例 1:

Java
// Java program to demonstrate
// asLifoQueue() method
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
 
        try {
 
            // creating object of Deque
            Deque deque = new ArrayDeque(7);
 
            // Adding element to deque
            deque.add(1);
            deque.add(2);
            deque.add(3);
            deque.add(4);
            deque.add(5);
 
            // get queue from the deque
            // using asLifoQueue() method
            Queue nq = Collections.asLifoQueue(deque);
 
            // printing the Queue
            System.out.println("View of the queue is: " + nq);
        }
        catch (IllegalArgumentException e) {
 
            System.out.println("Exception thrown : " + e);
        }
    }
}


Java
// Java program to demonstrate
// asLifoQueue() method
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
 
            // creating object of Deque
            Deque deque = new ArrayDeque(7);
 
            // Adding element to deque
            deque.add("Ram");
            deque.add("Gopal");
            deque.add("Verma");
 
            // get queue from the deque
            // using asLifoQueue() method
            Queue nq = Collections.asLifoQueue(deque);
 
            // printing the Queue
            System.out.println("View of the queue is: " + nq);
        }
        catch (IllegalArgumentException e) {
 
            System.out.println("Exception thrown : " + e);
        }
    }
}


输出:
View of the queue is: [1, 2, 3, 4, 5]

示例 2:

Java

// Java program to demonstrate
// asLifoQueue() method
 
import java.util.*;
 
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
 
            // creating object of Deque
            Deque deque = new ArrayDeque(7);
 
            // Adding element to deque
            deque.add("Ram");
            deque.add("Gopal");
            deque.add("Verma");
 
            // get queue from the deque
            // using asLifoQueue() method
            Queue nq = Collections.asLifoQueue(deque);
 
            // printing the Queue
            System.out.println("View of the queue is: " + nq);
        }
        catch (IllegalArgumentException e) {
 
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
View of the queue is: [Ram, Gopal, Verma]