java 栈 泛型_java 泛型栈(数组实现) | 学步园
嘗試將一些數據結構用java實現,嘗試過程中確實碰到一些問題,收獲很大import java.lang.reflect.Array;
class ArrayStack {
Class type;
private T[] values;
private int maxSize;
private int top;
public ArrayStack(Class type, int maxSize) {
this.type = type;
this.maxSize = maxSize;
//values = new T[maxSize];
values = (T[])Array.newInstance(type, maxSize);
top = -1;
}
public T pop() {
if(top == -1)
return null;
return values[top--];
}
public void push(T value) {
if(top == maxSize-1)
return;
values[++top] = value;
}
}
public class Test {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(Integer.class, 10);
for(int i=0; i<10; i++) {
stack.push(Integer.valueOf(i));
}
for(int i=0; i<10; i++) {
System.out.println(stack.pop());
}
ArrayStack stackOfChars = new ArrayStack(Character.class, 10);
for(int i=0; i<10; i++) {
stackOfChars.push((char)(i+65));
}
for(int i=0; i<10; i++) {
System.out.println(stackOfChars.pop());
}
}
}
總結
以上是生活随笔為你收集整理的java 栈 泛型_java 泛型栈(数组实现) | 学步园的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一个长方体玻璃容器从里面量长宽_泰来包装
- 下一篇: Docker安装ik分词器