在Java中,我想打印一个堆栈的内容。 所述toString()
方法打印它们由逗号分隔方括号包围: [foo, bar, baz]
。
现在的问题是,我该如何摆脱他们,只打印变量?
到目前为止我的代码:
Stack myStack = new Stack ();
for(int j=0;j<arrayForVar.length;j++) {
if(arrayForVar[j][1]!=null) {
System.out.printf("%s \n",arrayForVar[j][1]+"\n");
myStack.push(arrayForVar[j][1]);
}
System.out.printf("%s \n",myStack.toString());
这个答案为我工作:
使用toString
上堆栈方法,以及使用replaceAll
方法与blankstring取代方括号的所有实例。 像这样:
System.out.print(
myStack.toString().replaceAll("\\[", "").replaceAll("]", ""));
有一种变通方法。
你可以把它转换成数组,然后打印出这与Arrays.toString(Object[])
System.out.println(Arrays.toString(myStack.toArray()));
使用相同类型的循环,你用于填充堆栈,并打印自己的喜好单独的元素。 有没有办法改变的行为toString
,除非你去子类的路线Stack
,我不会推荐。 如果源代码Stack
是你的控制之下,那么刚修好的实现toString
那里。
使用toArray()
打印堆栈值
public void printStack(Stack<Integer> stack) {
// method 1:
String values = Arrays.toString(stack.toArray());
System.out.println(values);
// method 2:
Object[] vals = stack.toArray();
for (Object obj : vals) {
System.out.println(obj);
}
}
从toString()方法的文档AbstractCollection
。 所以,除非你定义你自己的,你不能这样做Stack
或者通过迭代实现自定义的toString() Stack
公共字符串的ToString()
返回此collection的字符串表示。 字符串表示形式由在它们通过其迭代器返回的顺序集合的元素的列表的,包含在方括号(“[]”)。 相邻的元件由字符“”(逗号和空间)分开。 这些元素通过String.valueOf(对象)转换为字符串。
此实现创建一个空字符串缓冲区,追加左方括号,并且在收集附加依次在每个元素的字符串表示迭代。 附加除了最后的每个元素之后,将字符串“”被附加。 最后,一个右支架被附加。 字符串被从字符串缓冲区获得,并返回。
Throwing a suggestion into the pool here. Depending on your Stack implementation this may or may not be possible.
The suggestion is an anonymous inner class for overriding the toString() in this particular case. This is one way to locally implement the subclassing Marko is mentioning. Your Stack instantiation would look something like
Stack s = new Stack(){
public String toString(){
// query the elements of the stack, build a string and
return nicelyFormattedString;
}
};
...
stack.forEach(System.out::println);
使用Java 8和更高流功能
尝试这个:
System.out.println(Arrays.asList(stackobject.toArray()));
System.out.println(Arrays.toString(stackobject.toArray()));