【问题标题】:Trouble showing the contents of a Stack无法显示堆栈的内容
【发布时间】:2015-03-03 07:20:14
【问题描述】:

我有一个堆栈接口和一个实现接口中方法的类(pushpopisEmptyisFull)。

我无法显示堆栈的内容。这是我的主要课程。

    StackInterface si = new MyStack();
    System.out.println("Stack is empty: "+si.isEmpty());

    si.push("Hello");
    si.push("Adam");
    si.push("Horrigan");
    si.isEmpty();
    si.pop();
    si.isFull();

    System.out.println(si);

输出是:

Stack is empty: true
stack.MyStack@15db9742

我在想,堆栈的内容怎么没有输出?

编辑,这里是 MyStack 类。

public class MyStack implements StackInterface {

    public ArrayList<String> theStack;

    public MyStack() {
        theStack = new ArrayList<String>();
    }

    public boolean isEmpty() {
        return theStack.isEmpty();
    }

    public boolean isFull() {
        return false;
    }

    public void push(Object newItem) {
        theStack.add((String) newItem);
    }

    public Object pop() {
        if (!(theStack.isEmpty())) {
            return theStack.remove(0);
        } else {
            return null;
        }
    }

}

【问题讨论】:

    标签: java methods interface stack


    【解决方案1】:

    您应该在您的 MyStack 类中覆盖 toString 以便它按您的意愿显示。 MyStack@15db9742ObjecttoString 的默认实现将返回的内容。

    例如:

    @Override
    public String toString ()
    {
        return theStack.toString();
    }
    

    【讨论】:

    • 你是什么意思? ArrayList 是 String 类型。
    • @AdamHorrigan 什么 ArrayList?我在您发布的代码中没有看到任何 ArrayList。
    • @AdamHorrigan 我明白了。我用一个可能的 toString 实现更新了我的答案。
    【解决方案2】:

    通过间接调用System.out.println(si) 调用堆栈的toString() 方法。可能这个方法没有被 Stack 类覆盖,这就是调用 Object 的 toString 方法的原因。这只是打印对象的类和地址 (stack.MyStack@15db9742)。

    解决方案是覆盖toString 方法并进行适当的实现以返回所需的字符串。

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 2015-07-28
      • 2021-02-06
      • 1970-01-01
      相关资源
      最近更新 更多