此处包括一个泛型顺序栈抽象类,一个Integer型实现类,一个测试类。
实现了栈的以下功能:
1.入栈
2.出栈
3.判空
4.求长度
5.取栈顶
6.扩充长度
泛型顺序栈抽象类
Stack.java:
package stack;
import java.lang.reflect.Array;
import java.util.Arrays;
public abstract class Stack<T>{
private int maxSize;
protected T arr[];
private int top;
public Stack(Class<T> componentType) {
this.maxSize = 1024;
this.arr = (T[])Array.newInstance(componentType, this.maxSize);
this.top = 0;
}
public Stack(Class<T> componentType, int maxSize) {
this.maxSize = maxSize;
this.arr = (T[])Array.newInstance(componentType, this.maxSize);
this.top = 0;
}
public int getSize() {
return top;
}
public int getMaxSize() {
return maxSize;
}
public void expandMaxSize(int maxSize) {
Arrays.copyOf(arr, this.maxSize + maxSize);
this.maxSize += maxSize;
}
public void push(T data) {
if(this.top > this.maxSize) {
throw new IllegalArgumentException("new element will be out of limits.");
}
arr[this.top] = data;
this.top++;
}
public T pop() {
if(this.top == 0) {
throw new IllegalArgumentException("this stack is already empty");
}
this.top--;
return arr[this.top];
}
public T peek() {
if(this.top == 0) {
throw new IllegalArgumentException("this stack is already empty");
}
return arr[this.top - 1];
}
public boolean isEmpty() {
return this.top == 0 ? true : false;
}
}
Integer型实现类
IntegerStack.java:
package stack;
public class IntegerStack extends Stack<Integer> {
public IntegerStack() {
super(Integer.class);
}
public IntegerStack(int maxSize) {
super(Integer.class, maxSize);
}
public void print() {
System.out.println("top");
System.out.println("------");
for(int i = this.getSize() - 1; i >= 0; i--) {
System.out.println(arr[i]);
}
System.out.println("------");
System.out.println("bottom");
}
}
测试类
IntegerStackDemo.java:
package stack;
public class IntegerStackDemo {
public static void main(String[] args) {
IntegerStack test = new IntegerStack();
System.out.println("size is: " + test.getSize());
System.out.println("is empty: " + test.isEmpty());
test.print();
System.out.println("================");
test.push(2);
test.push(5);
test.push(7);
test.push(8);
System.out.println("size is: " + test.getSize());
System.out.println("is empty: " + test.isEmpty());
test.print();
System.out.println("================");
System.out.println("first element is: " + test.peek());
test.pop();
System.out.println("first element is: " + test.peek());
System.out.println("size is: " + test.getSize());
test.print();
System.out.println("================");
}
}
输出结果:
size is: 0
is empty: true
top
------
------
bottom
================
size is: 4
is empty: false
top
------
8
7
5
2
------
bottom
================
first element is: 8
first element is: 7
size is: 3
top
------
7
5
2
------
bottom
================