给定以下类定义ArrayStack
:
Public class ArrayStack<T> implements Stack {
T[] stack;
int topIndex = -1;
在类 ArrayStack 中编写一个 equals(Stack other) 方法,该方法将 Stack 作为参数,如果两个堆栈相等则返回 true,否则返回 false。
public boolean equals(Stack<T> other) {
ArrayStack.java 的代码
import java.util.Arrays;
import java.util.EmptyStackException;
public class ArrayStack<T> implements Stacks<T> {
T[] stack;
int topIndex = -1;
private final static int DEFCAP = 100;
public ArrayStack(int maxSize) {
stack = (T[]) new Object[maxSize];
}
public ArrayStack() {
this(DEFCAP);
}
@Override
public void push(T element) {
if (topIndex == stack.length - 1) {
enlarge();
}
topIndex++;
stack[topIndex] = element;
}
@Override
public T pop() {
return stack[topIndex--];
}
@Override
public boolean isEmpty() {
return topIndex == -1;
}
@Override
public T peak() {
if (!isEmpty()) {
return stack[topIndex];
} else {
throw new EmptyStackException();
}
}
private void enlarge() {
stack = Arrays.copyOf(stack, stack.length + DEFCAP);
}
}
我的尝试:我对我的尝试有多糟糕感到非常生气,但我现在太封闭了,我无法正常思考。需要您的帮助来思考这个问题!
public boolean equals(Stack<T> other) {
if(! other.isEmpty() ) {
for(int i=0; i < stack.length; i++) {
if(stack[i].equals(Other.stack[i]) ) {
return true;
}
}
}
return false;
}
谢谢!