Java堆栈简单实现

public class StackTest {

    /**
     * don't initialize,while initial in constructors
     */
    private int CAPACITY;
    private int[] data;
    private int top;

    public StackTest(int capacity){
        if(capacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+capacity);
        this.CAPACITY = capacity;
        data = new int[CAPACITY];
        top = -1;
    }

    /**
     * provide default constructor
     */
    public StackTest(){
        this(10);
    }

    public void push(int value){
        if(isFull())
            throw new IllegalAccessError("Stack is Full Out of Space");
        data[++top] = value;
    }

    public int pop(){
        if(isEmpty())
            throw new EmptyStackException("Stack is Empty Already");
        return data[top--];
    }

    public int peek(){
        if(isEmpty())
            throw new EmptyStackException("Stack is Empty Already");
        return data[top];
    }

    public boolean isFull(){
        return (top == CAPACITY-1);
    }

    public boolean isEmpty(){
        return (top == -1);
    }

    public static void main(String[] args) {
        // 自己写简单的堆栈
        Random random = new Random();
        int STACK_SIZE = 10;
        StackTest stackTest = new StackTest();
        for(int i=0;i<STACK_SIZE;i++){
            stackTest.push(random.nextInt(100));
        }

//      stackTest.push(10);

        for(int i=0;i<STACK_SIZE;i++){
            System.out.println(stackTest.pop());
        }

        stackTest.peek();
    }
}
public class EmptyStackException extends RuntimeException {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    /**
     * 函数重载原则:两同一不同,即同一个类中函数名相同,参数列表不同(参数个数及参数类型)
     * 函数返回值、修饰符与重载没有关系
     */
    public EmptyStackException(){
        super();
    }

    public EmptyStackException(String message){
        super(message);
    }
}
public class FullStackException extends RuntimeException {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public FullStackException(){
        super();
    }

    public FullStackException(String message){
        super(message);
    }
}

注意几点:
1、最好提供默认构造函数
2、恰当使用函数重载:
函数重载原则:两同一不同,即同一个类中函数名相同,参数列表不同(参数个数及参数类型)
函数返回值、修饰符与重载没有关系
3、代码精简:如 data[++top] = value; return data[top–];
4、理解运行时异常(unchecked exception)
(1)方法调用链:方法间调用嵌套顺序
(2)异常传播:默认情况下,unchecked exception会沿着方法调用链进行传播,直到异常在其中一个方法当中被捕获处理,如果都不捕获,最终会被JVM捕获
(3)JVM默认异常处理:
1)打印异常描述信息
2)打印方法调用链(树结构)
3)停止当前应用程序
(4)throw可以抛出checked exception和unchecked exception
(5)throws一般用来声明checked exception

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值