11.7 编写程序,实现一个对象栈类MyStack,要求使用ArrayList类实现该栈,该栈类的UML图如下:
package com.leox;
import java.util.ArrayList;
/**
* @Description TODO
* @Author xrxleo
* @Date 2020/12/18 4:43 下午
*/
public class MyStack<T> {
private ArrayList<T> list;
public MyStack(){
list = new ArrayList<>();
}
//元素入栈的方法
public void push(T obj){
list.add(0,obj);
}
//删除栈顶元素
public T pop(){
return list.remove(0);
}
//返回栈顶元素
public T peek(){
return list.get(0);
}
//返回栈的大小
public int getSize(){
return list.size();
}
//判断栈是否是空
public boolean isEmpty(){
if(list.isEmpty()) {
return true;
}else {
return false;
}
}
//查找元素
public int search(T t){
return list.indexOf(t);
}
public static void main(String[] args) {
MyStack<Integer> integerMyStack = new MyStack<>();
integerMyStack.push(new Integer(9));
integerMyStack.push(new Integer(8));
integerMyStack.push(new Integer(7));
System.out.println(integerMyStack.search(7));
System.out.println(integerMyStack.pop());
System.out.println(integerMyStack.pop());
System.out.println(integerMyStack.pop());
System.out.println(integerMyStack.isEmpty());
System.out.println(integerMyStack.getSize());
}
}