使用java模拟对象在栈中压栈和弹栈的动作
package Array2;
public class Array2Homework01 {
public static void main(String[] args) {
Static s = new Static();
//压栈十一次
for (int i = 0; i < 11; i++) {
s.push(new Object());
}
for (int i = 0; i < 11; i++) {
s.pop(new Object());
}
}
}
class Static{
private Object[] o;
private int index;
//因为数据的变量初始化是在构造方法执行的时候所以,在构造方法赋值执行时一样的。
public Static() {
this.o = new Object[10];
this.index = -1;
}
//压栈的方法
public void push(Object obj){
if(index >= this.o.length -1){
System.out.println("压栈失败,栈已满");
return;
}else {
//如果输出的是引用默认调用toString方法
++index;
o[index] = obj;
System.out.println("此时指针指向"+index+"压进去的对象是"+this.o[index].toString());
}
}
public Object pop(Object obj){
if (index <0){
System.out.println("弹栈失败栈是空的");
return null;
}else {
System.out.println("此时指针指向"+index+"弹出去的对象是"+this.o[index]);
index--;
return obj;
}
}
public Object[] getO() {
return o;
}
public void setO(Object[] o) {
this.o = o;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
下面是运行结果展示
上面是老师写出来的下面是小白(我写的代码)
package Array2;
public class ArrayHome01 {
public static void main(String[] args) {
Object[] ars = new Object[10];
MyStack my = new MyStack(ars);
my.push(12);
}
}
class MyStack{
private int index = 0;
Object[] obj = new Object[10];
public MyStack() {
}
public MyStack( Object[] obj) {
this.obj = obj;
}
public void push(int a){
if(a+index == 10){
System.out.println("压栈"+a+"次");
index = index + a;
System.out.println("栈中现在有"+index+"个元素");
}else if(index+a > 10){
System.out.println("栈满了");
}
}
public void pop(int a){
if(index == 0){
System.out.println("栈最小了");
}else{
System.out.println("弹栈"+a+"次");
index = index - a;
System.out.println("栈中现在有"+index+"个元素");
}
}
}```