【问题标题】:Implementing a stack in Java在 Java 中实现堆栈
【发布时间】:2021-06-24 01:45:42
【问题描述】:

我是一名大学生,试图在我的数据结构课程中实现堆栈。我的教授让我们使用继承实现一个堆栈。我不习惯使用继承和扩展类,所以我对他的 TODO: cmets 指定的内容有点困惑。我想我只需要前一两个 cmets 的建议,然后我应该能够解决剩下的问题。

我填写了我认为我应该如何做,但它的措辞让我觉得我做错了。我不明白为什么“super”和“this”是合法的但不是必需的?这是否意味着我可以说 add(item);会没事的吗?

@SuppressWarnings("serial")
public class Stack<T> extends ArrayList<T> {
    // TODO 1: declare a private integer member named "cursor" and initialize it to
    // -1

        private int cursor = -1;

    /**
     * Push the passed item of type T onto the stack. This is equivalent to calling
     * the add function inherited from ArrayList.
     *
     * @param item the item to be pushed onto the stack.
     */
    public void push(T item) {
        // TODO 2: add the item passed as a parameter using the add function inherited
        // from the ArrayList super class. Hint: it is legal but unnecessary to use the
        // syntax "super." or "this." to call the add function.
        super.add(item);
    }

【问题讨论】:

    标签: java inheritance stack push


    【解决方案1】:

    你有Stack extends ArrayList

    Stack 不会覆盖add 函数,因此super 不是必需的。

    super 调用扩展类的函数 (ArrayList)

    【讨论】:

      猜你喜欢
      • 2019-11-11
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 2013-12-18
      • 2021-10-30
      • 2021-06-06
      相关资源
      最近更新 更多