0

给定以下类定义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;
}

谢谢!

4

3 回答 3

4
public boolean equals(Stack<T> other) {
    //If they point to the same object return true
    if (stack == other) return true;
    //Check for nulls
    if (stack == null || other == null) return false;
    //If the stacks are not the same length, then they won't be equal, easy first test case
    if (stack.length != other.size()) return false;

    for(int i=0; i < stack.length; i++) {
           //Step through each item in both stacks, if any don't match return false
           if(!stack[i].equals(other.stack[i]) ) {
                  return false;
           }
    }

    //Haven't returned yet, they must be equal
    return true;
}
于 2013-05-31T19:58:25.093 回答
0

您的 equals 实现显然是错误的。如果只有一个元素匹配,则返回 true。这意味着,您唯一会得到错误的是,当所有条目一对一不匹配时。

您正在寻找的是返回 false,如果任何相应的元素不匹配并在运行循环结束时返回 true。

如果两个堆栈的大小不同,您还必须返回 false。

于 2013-05-31T19:55:45.497 回答
0

您可以在java中使用String.valueOf()方法,该方法将不同类型的值转换为字符串。

如果 s 和 t 是两个堆栈对象

String a = String.valueOf(s);
String b= String.valueOf(t);

return a.equals(b); // will return true if stacks are equal 

如果任何堆栈为空,此方法也会小心。

于 2019-01-10T11:16:13.773 回答