我的任务是将一些代码从使用 Int[] 转换为使用 ArrayList。这样做时,我只允许编辑这些方法:Stack(int)、getStack()、setStack()、stackRead() 和 stackWrite()。当我这样做时,我会收到大量关于不同类型匹配的错误。
如前所述,我只能编辑 Stack(int)、getStack()、setStack()、stackRead() 和 stackWrite()。在编辑这些我想出了下面的代码:
我的目标是让这段代码使用 ArrayList,但它会产生很多问题,我尝试更改与泛型相关的所有内容并解析为 Int,但它给出了超出范围的错误。
我已经尝试使用 .toArray 将 getStack() 更改为一个对象,它仍然给我 ArrayIndexOutofBounds
public class Stack<E> {
/**
* This ArrayList stores the values on the Stack, i.e., it is *the stack*.
*/
private ArrayList<E> mStack;
/**
/**
* Default constructor. Creates a Stack with capacity of 10 ints.
*/
public Stack() {
this(10);
}
/**
* This constructor creates a Stack with capacity of pCapacity. It initializes all three of
* the data members.
*
* @param pCapacity - The capacity of the Stack.
*/
public Stack(int pCapacity) {
setCapacity(pCapacity);
setStack(new ArrayList<E>(mCapacity));
setTop(0);
}
private ArrayList<E> getStack() {
return mStack;
}
public int peek() {
return (int)stackRead(getTop());
}
/**
* Removes the top element from the Stack.
*
* @return The top value.
*/
public int pop() {
int topValue = peek();
stackWrite(getTop(), 0);
decTop();
return topValue;
}
/**
* Pushes pValue onto the top of the stack.
*
* @param pValue - The value to be pushed onto the top of the stack.
*
* @return A reference to the Stack. This permits operations such as:
* myStack.push(1).push(2).push(3).push(4).
*/
public Stack push(int pValue) {
stackWrite(incTop(), pValue);
return this;
}4
/**
* Gets the value at index pIndex from the stack data structure and returns the value.
*
* @param pIndex the index into mStack where we are reading a value.
* @return The value at pIndex.
*/
private E stackRead(int pIndex) {
return getStack().get(pIndex);
}
/**
* Puts pValue into the stack data structure at index pIndex.
*
* @param pIndex The inex into mStack where we are writing pValue.
* @param pValue The value to be writtin into mStack.
*
* @return pValue.
*/
private int stackWrite(int pIndex, int pValue) {
//getStack().set(pIndex, pValue);
return pValue;
}
}
不知何故,需要编写代码以便只编辑允许的方法,同时从一维数组更改为通用数组列表