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


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


Java Deque 接口的 peek() 方法用於檢索但不移除雙端隊列的頭部。如果給定的雙端隊列為空,則該方法可能返回 null。

指定者:

  • 查看接口 Queue<E>

用法:

E    peek()

參數:

NA

返回:

上述方法用於返回由隊列表示的雙端隊列的頭部。另一方麵,如果雙端隊列為空,則該方法可能返回 null。

例子1

import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequepeekExample1 {
    public static void main(String[] args) {
		Deque<Character> deque = new ArrayDeque<>();
		deque.offer('J');
		deque.offer('A');
		deque.offer('V');
		deque.offer('A');
		deque.offer('T');
		deque.offer('P');
		deque.offer('O');
		deque.offer('I');
		deque.offer('N');
		deque.offer('T');
		Character val = deque.peek();
		System.out.println("The first character is given as:"+val);
		System.out.println("The deque is:");
		for (Character character:deque) {
			System.out.println(character);
		}   	
	}
}

輸出:

The first character is given as:J
The deque is:
J
A
V
A
T
P
O
I
N
T

例子2

import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequepeekExample2 {
    public static void main(String[] args) {
		Deque<String> deque = new ArrayDeque<>();
		deque.offer("Hello");
		deque.offer(" ");
		deque.offer("World");
		String val = deque.peek();
		System.out.println("The first string is given as:"+val);
		System.out.println("The deque is:"+deque);
	}
}

輸出:

The first string is given as:Hello
The deque is:[Hello,  , World]

例子3

import java.util.ArrayDeque;
import java.util.Deque;
public class JavaDequepeekExample3 {
   public static void main(String[] args) {
	 Deque<Long> deque = new  ArrayDeque<>();
	    deque.offer(88l);
	    deque.offer(78l);
	    deque.offer(67l);
	   Long val = deque.peek();
	System.out.println("The first long value is given as:"+val);
	System.out.println("The resultant deque is:"+deque);  
   }
}

輸出:

The first long value is given as:88
The resultant deque is:[88, 78, 67]




相關用法


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