【问题标题】:Why still get [ ] after using toString method? [duplicate]为什么使用 toString 方法后仍然得到 [ ] ? [复制]
【发布时间】:2015-02-18 20:28:38
【问题描述】:

这是我的代码:

public class StackStudy{
    public static void main(String[] args){
        Stack<String> st = new Stack<String>();
        st.push("hi");
        st.push("bye");
        st.push("awful");
        System.out.println(st.toString());
    }
}

控制台打印出这个:

[hi, bye, awful]

我以为用toString会去掉[],为什么还在呢?

编辑: 如果 toString 不是摆脱[]的正确方法,那么正确的方法是什么?

【问题讨论】:

  • 你为什么认为toString 会去掉括号?
  • 这是默认实现。
  • It is hard coded in the source code。正确的方法?创建一个打印内容的自己的方法。
  • 不要使用 toString() 依赖特定的输出格式
  • 我会在 dup Q/A 中选择 this answer

标签: java stack tostring


【解决方案1】:

因为Vector(或者可能是AbstractCollection)的toString() 方法包括括号(并且Stack 继承了toString())。您可以通过像

这样的子字符串来删除它们
String str = st.toString();
System.out.println(str.substring(1, str.length() - 1));

【讨论】:

  • 括号来自AbstractCollection,而不是Vector:P。
【解决方案2】:

覆盖 toString() 使您可以完全控制返回的内容。因此,您可以跳过括号。但是,您只调用了 toString() 方法(实际上 System.out.println() 也是这样做的。因此,结果符合预期。

【讨论】:

    【解决方案3】:

    以下代码可以解决问题。

    public class StackStudy{
        public static void main(String[] args){
            Stack<String> st = new Stack<String>();
            st.push("hi");
            st.push("bye");
            st.push("awful");
            String stackAsString = st.toString();
            System.out.println(stackAsString.substring(1, stackAsString.length() - 1));
        }
     }
    

    【讨论】:

    • 试过但没用,不确定我是否理解这部分:String stackAsString = st.toString(); System.out.println(stackAsString.substring(1, stackAsString.length() - 1));
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    相关资源
    最近更新 更多