/*
编写程序,使用一维数组,模拟栈数据结构。
要求:
1、这个栈可以存储java中的任何引用类型的数据。
2、在栈中提供push方法模拟压栈。(栈满了,要有提示信息。)
3、在栈中提供pop方法模拟弹栈。(栈空了,也有有提示信息。)
4、编写测试程序,new栈对象,调用push pop方法来模拟压栈弹栈的动作。
5、栈的数量默认为10。
/
在这里插入代码片
package com.immortalize;//导包
import java.lang.;//导库
public class Stack {
//obj数组和index变量私有化
private Object[] obj=new Object[10];
private int index;
//构造方法
public Stack() {
index=-1;
}
//压栈方法
public void push(Object object){
if(index >= obj.length-1){
System.out.println("压栈失败,栈已满!");
return;
}
index++;
obj[index]=object;
System.out.println("压栈"+object+"成功,栈帧指向"+index);
}
//弹栈方法
public void pop(){
if(index<0){
System.out.println("弹栈失败,栈已空!");
return;
}
System.out.print("弹栈"+obj[index]+"成功");
index--;
System.out.println("栈帧指向"+index);
}
//封装index变量 setter and getter
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
//封装obj数组 setter and getter
public Object[] getObj() {
return obj;
}
public void setObj(Object[] obj) {
this.obj = obj;
}
}
测试主方法类:
在这里插入代码片
package com.immortalize;//导包
//测试Stack功能
public class StackTest {
public static void main(String[] args) {
Stack stack=new Stack();
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.push(new Object());
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
}
}
运行效果图: