gpt4 book ai didi

java - 为什么使用toString方法后仍然得到[]?

转载 作者:行者123 更新时间:2023-12-02 05:08:16 26 4
gpt4 key购买 nike

这是我的代码:

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 不是摆脱 [] 的正确方法,那么正确的方法是什么?

最佳答案

因为 Vector (或可能 AbstractCollection)的 toString() 方法包含括号(和 Stack继承了 toString())。您可以通过使用子字符串来删除它们,例如

String str = st.toString();
System.out.println(str.substring(1, str.length() - 1));

关于java - 为什么使用toString方法后仍然得到[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27573904/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com