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 に答える