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