Reputation: 35
i have a class for List, Node, and Stack.
The classes List, Node are all done, now i want to finish my Stack.class, which uses my List.class. Now i am in my main method and i want to try out my push/pop methods, but don't know how to output them as strings.
I did this in my List.class, but don't know how to recreate it for the Stack.class.
Can someone help me? Thanks.
public class Stack {
private List list;
public Stack() {
list = new List();
}
public class List{
public String toString() {
Node temp = head;
String string = "";
while (temp != null && temp.getNext() != null) {
string = string + temp.getElement() + ", ";
temp = temp.getNext();
}
if (temp != null) {
string = string + temp.getElement() + ".";
}
return string;
}
Upvotes: 1
Views: 185
Reputation: 2050
You can handle each element in the list:
For example, if you need get list values by comma separate:
public String toString() {
return list.stream()
.map(Objects::toString)
.collect(Collectors.joining(","));
}
Or you need also modify each value:
public String toString() {
return list.stream()
.map(p -> "[" + p.toString() + "]")
.collect(Collectors.joining(","));
}
Upvotes: 0
Reputation: 68
you have to "concatenate" the 2 toString() method. So you have to create a new toString() in your Stack class.
public class Stack {
private List list;
public Stack() {
list = new List();
}
public String toString()
{
String myreturn = "//Anything you need" + list.toString();
return myreturn;
}}
Upvotes: 1
Reputation: 201439
In your Stack
class, you could invoke list.toString()
. Something like
public String toString() {
return String.format("Stack: %s", list.toString());
}
Upvotes: 2