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


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


Deque 接口的 removeFirst() 方法用於檢索和刪除給定雙端隊列的第一個元素。上述方法與 pollFirst() 方法不同,如果給定的雙端隊列為空,則拋出異常。

用法:

public E removeFirst()

參數:

NA

返回:

上述方法用於返回給定雙端隊列的頭部。

拋出:

NoSuchElementException- 如果給定的雙端隊列為空。

例子1

import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequeremoveFirstExample1 {
   public static void main(String[] args) {
	Deque<String> deque = new ArrayDeque<>();
	 deque.offer("Welcome");
	 deque.offer("to");
	 deque.offer("our");
	 deque.offer("site"); 
	   String val = deque.removeFirst();
	   System.out.println("The removed string is:"+val);
      System.out.println("The resultant deque is:");
      for (String string:deque) {
		System.out.println(string);
	}
   }
}

輸出:

The removed string is:Welcome
The resultant deque is:
to
our
site

例子2

import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequeremoveFirstExample2 {
   public static void main(String[] args) {
	Deque<Integer> deque = new ArrayDeque<>();
	 deque.offer(66);
	 deque.offer(11);
	 deque.offer(33);
	 deque.offer(44); 
	  int val = deque.removeFirst();
	   System.out.println("The removed integer value is:"+val);
      System.out.println("The resultant deque is:");
      for (Integer integer:deque) {
		System.out.println(integer);
	     }
    }
}

輸出:

The removed integer value is:66
The resultant deque is:
11
33
44

例子3

import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequeremoveFirstExample3 {
   public static void main(String[] args) {
	Deque<Long> deque = new ArrayDeque<>();
	 deque.offer(11l);
	 deque.offer(88l);
	 deque.offer(22l);
	 deque.offer(99l); 
	  Long val = deque.removeFirst();
	   System.out.println("The removed long value is:"+val);
      System.out.println("The resultant deque is:");
      for (Long long1:deque) {
		System.out.println(long1);
	   }
    }
}

輸出:

The removed long value is:11
The resultant deque is:
88
22
99




相關用法


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