您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)在Java中如何使用數(shù)組實(shí)現(xiàn)堆棧,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
棧的要求是:
1) 棧有一個(gè)構(gòu)造函數(shù),它接受一個(gè)數(shù)字來初始化它的大小,
2) ??梢匀菁{任何類型的元素,
3) 棧有一個(gè) push() 和一個(gè) pop() 方法。
public class Stack<E> {
private E[] arr = null;
private int CAP;
private int top = -1;
private int size = 0;
@SuppressWarnings("unchecked")
public Stack(int cap) {
this.CAP = cap;
this.arr = (E[]) new Object[cap];
}
public E pop() {
if(this.size == 0){
return null;
}
this.size--;
E result = this.arr[top];
this.arr[top] = null;//prevent memory leaking
this.top--;
return result;
}
public boolean push(E e) {
if (isFull())
return false;
this.size++;
this.arr[++top] = e;
return true;
}
public boolean isFull() {
if (this.size == this.CAP)
return false;
return true;
}
public String toString() {
if(this.size==0){
return null;
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<this.size; i++){
sb.append(this.arr[i] + ", ");
}
sb.setLength(sb.length()-2);
return sb.toString();
}
public static void main(String[] args) {
Stack<String> stack = new Stack<String>(11);
stack.push("hello");
stack.push("world");
System.out.println(stack);
stack.pop();
System.out.println(stack);
stack.pop();
System.out.println(stack);
}
}
輸出:
hello, world hello null
這個(gè)例子在“Effective Java”中使用了兩次。首先,堆棧示例用于說明內(nèi)存泄漏。其次,這個(gè)例子是用來說明我們什么時(shí)候可以抑制未經(jīng)檢查的警告。
關(guān)于“在Java中如何使用數(shù)組實(shí)現(xiàn)堆棧”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。