求助!如何用Java编写一个栈
老师让写一个Java编一个实用的栈类,要求能够处理所有类型.
提示说可以用Object和包装类型处理所有的情况,但是我还是不是很明白,有哪位高手能给点建议或是部分代码帮帮忙呢?谢了
------解决方案--------------------首先是抽象类
package com.sohu.blog.denns_zane.stackqueue;
/** *//**
* @author dennis
*
*/
public abstract class AbstractStack {
public abstract Object pop();
public abstract void push(Object obj);
public abstract Object topEl();
public abstract boolean isEmpty();
public abstract void clear();
}
/** *//**
*
*/
package com.sohu.blog.denns_zane.stackqueue;
然后是实现类,采用ArrayList做实现:
/** *//**
* @author dennis
*
*/
public class Stack extends AbstractStack {
private java.util.ArrayList pool = new java.util.ArrayList();
public Stack() {
}
public Stack(int n) {
pool.ensureCapacity(n);
}
public void clear() {
pool.clear();
}
public boolean isEmpty() {
return pool.isEmpty();
}
public Object topEl() {
if (isEmpty())
throw new
java.util.EmptyStackException();
return pool.get(pool.size() - 1);
}
public Object pop() {
if (isEmpty())
throw new java.util.EmptyStackException();
return pool.remove(pool.size() - 1);
}
public void push(Object el) {
pool.add(el);
}
public String toString() {
return pool.toString();
}
}