package com.matao.fundamentals;

/**
 * Created by matao on 5/27/16.
 * 定容栈
 */
public class FixedCapacityStack<T> {
    private T[] array;
    private int size;       // 元素数量
    private int capacity;   // 容量

    public FixedCapacityStack(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        this.array = (T[]) new Object[capacity];
    }

    public void push(T item) {
        if (isFull()) {
            throw new RuntimeException("Fixed capacity stack overflow!");
        }
        array[size++] = item;
    }

    public T pop() {
        return array[--size];
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == capacity;
    }

    public int getSize() {
        return size;
    }

    public int getCapacity() {
        return capacity;
    }

    public static void main(String[] args) {
        FixedCapacityStack<Integer> fixedCapacityStack = new FixedCapacityStack<>(3);
        System.out.println("-------------- after initial -------------------");
        System.out.println("capacity: " + fixedCapacityStack.getCapacity());
        System.out.println("size: " + fixedCapacityStack.getSize());
        System.out.println("isEmpty: " + fixedCapacityStack.isEmpty());

        fixedCapacityStack.push(1);
        System.out.println("-------------- after push 1 item -------------------");
        System.out.println("capacity: " + fixedCapacityStack.getCapacity());
        System.out.println("size: " + fixedCapacityStack.getSize());
        System.out.println("isEmpty: " + fixedCapacityStack.isEmpty());

        fixedCapacityStack.push(2);
        fixedCapacityStack.push(3);
        System.out.println("-------------- after push another 2 items -------------------");
        System.out.println("capacity: " + fixedCapacityStack.getCapacity());
        System.out.println("size: " + fixedCapacityStack.getSize());
        System.out.println("isEmpty: " + fixedCapacityStack.isEmpty());

        fixedCapacityStack.push(4);
        System.out.println("-------------- after push another 1 item, stack over flow -------------------");
        System.out.println("capacity: " + fixedCapacityStack.getCapacity());
        System.out.println("size: " + fixedCapacityStack.getSize());
        System.out.println("isEmpty: " + fixedCapacityStack.isEmpty());
    }
}

@@ -69,11 +69,35 @@
 %0A * 
-%E5%AE%9A%E5%AE%B9%E6%A0%88
+%3Cp%3E%0A * Fixed Capacity Stack
 %0A */
@@ -192,12 +192,34 @@
  // 
-%E5%85%83%E7%B4%A0%E6%95%B0%E9%87%8F
+current size of this stack
 %0A   
@@ -250,10 +250,40 @@
  // 
-%E5%AE%B9%E9%87%8F
+the fixed capacity of this stack
 %0A%0A  
@@ -379,24 +379,112 @@
 s.size = 0;%0A
+        // generic array creation is disallowed in Java. Instead, we need to use a cast%0A
         this

revise comments