第一回写的用arraylist模拟栈操作

package hashMap;
import java.util.ArrayList;
import d.Student;
/**
 * 用ArrayList模拟栈操作
 * @author zhujiabin
 * @see 2016年7月14日
 */

public class Stack
{
    ArrayList<Student> al=new ArrayList<Student>();
    public Object peek()
    {
        return al.get(0);
    }
    public Object pop()//出栈
    {
        return al.remove(al.size()-1);
    }
    public void push(Student o)//进栈
    {
        al.add(o);
    }
    public void clear()//将栈置空
    {
        al.clear();
    }
    public boolean isEmpty()//判断栈是否是空
    {
        if(al.isEmpty())
        {
            return true;
        }
        else 
        {
            return false;
        }
    }
    public Object getIndex(int i)//返回指定下标出的值
    {
        return al.get(i);
    }
}

测试:

package hashMap;
import d.Student;
/**
 * 用ArrayList模拟栈操作
 * @author 郑云飞
 * @see 2010年8月14日
 */
public class StackTest
{
    public static void main(String[] args)
    {
        Stack s1=new Stack();
        s1.push(new Student("庄子",200));
        s1.push(new Student("老子",200));
        s1.push(new Student("梦子",200));
        s1.push(new Student("荀子",200));
        while(!s1.isEmpty())
        {
            System.out.println(s1.pop());//出栈输出内容
        }
        
    }
}
 
package hashMap;
/**
 * 用ArrayList模拟栈操作
 * @author zhujiabin
 * @see 2016年7月14日
 */
public class Student
{
    String name;
    int age;
    public Student(String name,int age)
    {
        this.name=name;
        this.age=age;
    }
    public String toString()
    {
        return "姓名:" +name+"年龄:"+age;
    }
}
原文地址:https://www.cnblogs.com/zhujiabin/p/5690766.html