當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Deque poll()用法及代碼示例


Java Deque 接口的 poll() 方法用於檢索和移除 deque 的頭部。另一方麵,如果雙端隊列為空,則該方法可能返回 null。上述方法等價於pollFirst()。

指定者:

在接口 Queue<E> 中輪詢

用法:

public E poll()

參數:

NA

返回:

上述方法用於返回給定雙端隊列的第一個元素。否則,如果雙端隊列為空,該方法可能會返回空值。

例子1

import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequepollExample1 {
   public static void main(String[] args) {
	   Deque<Float> deque = new ArrayDeque<>();
	    deque.offerLast(45.6f);
		deque.offerLast(23f);
		deque.offerLast(45.8f);
		deque.offerLast(66.9f);
		Float val = deque.poll();
		System.out.println("The first element is:"+val);
		System.out.println("The final deque is given as:"+deque);
    }
}

輸出:

The first element is:45.6
The final deque is given as:[23.0, 45.8, 66.9]

例子2

import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequepollExample2 {
  public static void main(String[] args) {
	Deque<String> deque = new ArrayDeque<>();
	deque.offer("Java");
	deque.offer("is");	
	deque.offer("a");
	deque.offer("portable");
	deque.offer("language");
	String val = deque.poll();
   System.out.println("The first string value is:"+val);
   System.out.println("The final deque is given as:");
   for (String string:deque) {
	System.out.println(string);
    }
  }
}

輸出:

The first string value is:Java
The final deque is given as:
is
a
portable
language

例子3

import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequepollExample3 {
  public static void main(String[] args) {
	Deque<Integer> deque = new ArrayDeque<>();
	deque.offer(34);
	deque.offer(65);
	deque.offer(59);
	deque.offer(95);
	deque.offer(68);
	int val = deque.poll();
   System.out.println("The first string value is:"+val);
   System.out.println("The final deque is given as:");
  for (Integer integer:deque) {
	System.out.println(integer);
    }
  }
}

輸出:

The first string value is:34
The final deque is given as:
65
59
95
68




相關用法


注:本文由純淨天空篩選整理自 Java Deque poll() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。