Java ArrayDeque完成Stack的功效。本站提示廣大學習愛好者:(Java ArrayDeque完成Stack的功效)文章只能為提供參考,不一定能成為您想要的結果。以下是Java ArrayDeque完成Stack的功效正文
在J2SE6引入了ArrayDeque類,它繼續了Deque(雙向隊列)接口,應用此類可以本身完成java.util.Stack類的功效,去失落了java.util.Stack的多線程同步的功效。
例如創立一個寄存Integer類型的Stack,只需在類中創立一個ArrayDeque類的變量作為屬性,以後界說的出棧、入棧,不雅察棧頂元素的操作就直接操作ArrayDeque的實例變量便可。
import java.util.ArrayDeque; import java.util.Deque; public class IntegerStack { private Deque<Integer> data = new ArrayDeque<Integer>(); public void push(Integer element) { data.addFirst(element); } public Integer pop() { return data.removeFirst(); } public Integer peek() { return data.peekFirst(); } public String toString() { return data.toString(); } public static void main(String[] args) { IntegerStack stack = new IntegerStack(); for (int i = 0; i < 5; i++) { stack.push(i); } System.out.println(stack); System.out.println("After pushing 5 elements: " + stack); int m = stack.pop(); System.out.println("Popped element = " + m); System.out.println("After popping 1 element : " + stack); int n = stack.peek(); System.out.println("Peeked element = " + n); System.out.println("After peeking 1 element : " + stack); } }
java.util.ArrayDeque的源碼:
private transient E[] elements; private transient int head; private transient int tail; /*此處寄存e的地位是從elements數組最初的地位開端存儲的*/ public void addFirst(E e) { if (e == null) throw new NullPointerException(); elements[head = (head - 1) & (elements.length - 1)] = e;//初次數組容量默許為16,head=(0-1)&(16-1)=15 if (head == tail) doubleCapacity(); } /*每次擴容都按拔出的前後次序從新放入一個新的數組中,最新拔出的放在數組的第一個地位。*/ private void doubleCapacity() { assert head == tail; int p = head; int n = elements.length; int r = n - p; // number of elements to the right of p int newCapacity = n << 1; if (newCapacity < 0) throw new IllegalStateException("Sorry, deque too big"); Object[] a = new Object[newCapacity]; System.arraycopy(elements, p, a, 0, r); System.arraycopy(elements, 0, a, r, p); elements = (E[])a; head = 0; tail = n; } public E removeFirst() { E x = pollFirst(); if (x == null) throw new NoSuchElementException(); return x; } public E pollFirst() { int h = head; E result = elements[h]; // Element is null if deque empty if (result == null) return null; elements[h] = null; // 從新設置數組中的這個地位為null,便利渣滓收受接管。 head = (h + 1) & (elements.length - 1);//將head的值回退,相當於將棧的指針又向下挪動一格。例如,12--〉13 return result; } public E peekFirst() { return elements[head]; // elements[head] is null if deque empty }
以上就是本文的全體內容,願望對年夜家進修java法式設計有所贊助。