สร้าง Stack รับ Generic Type
2 min readMar 21, 2019
แบบง่ายๆ นะครับ
import java.lang.reflect.Array;
class Stack<T> {
private final T[] array;
public int index = -1;
public Stack(Class<T> tClass, int stackSize) {
array = (T[]) Array.newInstance(tClass, stackSize);
}
public void push(T t) {
array[++index] = t;
}
private T pop() throws Exception {
if (index < 0) {
throw new Exception("Stack is empty.");
}
return array[index--];
}
public static void main(String[] args) throws Exception {
Stack<String> stringStack = new Stack<String>(String.class, 50);
stringStack.push("Hello");
stringStack.push("Pee");
stringStack.push("Nok");
stringStack.push("Bee");
System.out.println(stringStack.index);
System.out.println(stringStack.pop());
System.out.println(stringStack.pop());
System.out.println(stringStack.pop());
System.out.println(stringStack.pop());
System.out.println(stringStack.pop());
System.out.println(stringStack.pop());
}
}
ผลที่ได้
อีกแบบใช้ List แทน Array นะครับ
import java.util.ArrayList;
import java.util.List;
class Stack<T> {
private List<T> mylist = new ArrayList<>();
public void add(T t) {
mylist.add(t);
}
private T get() throws Exception {
if (mylist.isEmpty()) {
return null;
}
final int index = mylist.size() - 1;
T t = mylist.get(index);
mylist.remove(index);
return t;
}
public static void main(String[] args) throws Exception {
Stack<Integer> stack = new Stack<>();
stack.add(1);
stack.add(2);
stack.add(3);
stack.add(4);
System.out.println(stack.get());
System.out.println(stack.get());
System.out.println(stack.get());
System.out.println(stack.get());
System.out.println(stack.get());
}
}
ผลที่ได้