Java Collections asLifoQueue() 方法



描述

Java Collections asLifoQueue(Deque<T>) 方法用於將 Deque 檢視作為後進先出 (Lifo) 佇列。

宣告

以下是 java.util.Collections.asLifoQueue() 方法的宣告。

public static <T> Queue<T> asLifoQueue(Deque<T> deque)

引數

deque − 這是 deque。

返回值

方法呼叫返回佇列。

異常

從整數集合獲取 LIFO 佇列示例

以下示例演示了 Java Collection asLifoQueue(Deque) 方法的使用,以獲取 LIFO 佇列。我們建立了一個包含一些整數的 Deque 物件。使用 asLifoQueue(Deque) 方法,我們獲取佇列,然後列印佇列。

package com.tutorialspoint;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.Queue;

public class CollectionsDemo {
   public static void main(String[] args) {
      // create an array deque
      Deque<Integer> deque = new ArrayDeque<>(Arrays.asList(20,30,20,30,15,22,11));

      // get queue from the deque
      Queue<Integer> nq = Collections.asLifoQueue(deque);      

      System.out.println("View of the queue is: "+nq);
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果。

View of the queue is: [20, 30, 20, 30, 15, 22, 11]

從字串集合獲取 LIFO 佇列示例

以下示例演示了 Java Collection asLifoQueue(Deque) 方法的使用,以獲取 LIFO 佇列。我們建立了一個包含一些字串的 Deque 物件。使用 asLifoQueue(Deque) 方法,我們獲取佇列,然後列印佇列。

package com.tutorialspoint;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.Queue;

public class CollectionsDemo {
   public static void main(String[] args) {
      // create an array deque
      Deque<String> deque = new ArrayDeque<>(Arrays.asList("Welcome","to","Tutorialspoint"));

      // get queue from the deque
      Queue<String> nq = Collections.asLifoQueue(deque);      

      System.out.println("View of the queue is: "+nq);
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果。

View of the queue is: [Welcome, to, Tutorialspoint]

從物件集合獲取 LIFO 佇列示例

以下示例演示了 Java Collection asLifoQueue(Deque) 方法的使用,以獲取 LIFO 佇列。我們建立了一個包含一些學生物件的 Deque 物件。使用 asLifoQueue(Deque) 方法,我們獲取佇列,然後列印佇列。

package com.tutorialspoint;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.Queue;

public class CollectionsDemo {
   public static void main(String[] args) {
      // create an array deque
      Deque<Student> deque = new ArrayDeque<>(Arrays.asList(new Student(1, "Julie"),
         new Student(2, "Robert"), new Student(3, "Adam")));

      // get queue from the deque
      Queue<Student> nq = Collections.asLifoQueue(deque);      

      System.out.println("View of the queue is: "+nq);
   }
}
class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果。

View of the queue is: [[ 1, Julie ], [ 2, Robert ], [ 3, Adam ]]
java_util_collections.htm
廣告

© . All rights reserved.