【发布时间】:2014-04-20 08:57:03
【问题描述】:
我需要修改一个类来创建一个动态数组堆栈。 此时我的代码如下所示:
public class DynamicArrayStack<E> implements Stack<E> {
private E[] elems; //used to store the elements
public static final int defaultIncrement = 25;
private final int increment;
private int top;
@SuppressWarnings( "unchecked" )
public DynamicArrayStack( int increment ) {
this.increment = increment;
elems = (E[]) new Object[ increment ];
top = 0;
}
/**
* Constructor with no parameter that will initialize
* the stack to have an array whose size is the value
* of increment and memorise that value as the value
* of increment.
*/
public void ArraySize() { }
public boolean isEmpty() {
return top == 0;
}
public E peek() {
return elems[ top-1 ];
}
public E pop() {
// save the top element
E saved = elems[ --top ];
// scrub the memory, then decrements top
elems[ top ] = null;
return saved;
}
public void push( E elem ) {
// stores the element at position top, then increments top
elems[ top++ ] = elem;
}
public String toString() {
StringBuffer b;
b = new StringBuffer( "DynamicArrayStack: {" );
for ( int i=top-1; i>=0; i-- ) {
if ( i!=top-1 ) {
b.append( "," );
}
b.append( elems[ i ] );
}
b.append( "}" );
return b.toString();
}
}
如何编辑第一个构造函数以将增量设置为堆栈的初始大小,以及在增加或减少数组大小时使用的相同值。我这样做的方法似乎太简单了。参数必须 > 0 并且当数组大小改变时添加或删除固定数量的单元格。
第二个构造函数应该将堆栈设置为一个数组,其大小是增量值。我在这里不断收到错误,因为我不知道该怎么做,因为我认为这已经在第一个构造函数中设置了。还将数组的大小作为增量值。
另外我如何使这个类能够改变堆栈的容量以及我应该将该代码放置到哪个方法中?
【问题讨论】:
-
请同时提及进口。
-
带有 javadoc 的方法不是构造函数 - 名称与类不匹配,它返回
void。如果increment > 0,实际构造函数中的while循环不会永远继续吗?目前尚不清楚它将如何退出。 -
另外,您尝试实现的
Stack接口是什么。 java.util.Stack 是一个你需要extend而不是implement的类。 -
public DynamicArrayStack 是第一个构造函数,public void ArraySize() 是第二个。空白只是为了让课程继续编译,直到我得到正文。课程的主体应该是正确的(它是作为框架提供给我的)。这是我需要指导的其余部分。