Reputation: 9
I'm trying to figure out how to output all the versions of the node "latest" using a toString method, but I'm confused as to how to make the while loop work correctly in this case. I was wondering if there is a method to go about doing so.
Here's the toString()
method:
public String toString() {
String output = "key: " + key ;
Node<VersionedObject> currNode = latest;
while (latest != null){
output += latest+ "\n\t";
latest.setNext(latest);
} // This isn't particularly working
//return "key: " + key +"\n\t" +latest + "\n\t" + latest.getNext(); // placeholder but it's getting closer. This one is INSANELY specific
return output;
}
, Here's the method that creates the list:
public StackOfVersionedObjects(String key, final Object object) {
this.key = key;
VersionedObject vrObject = new VersionedObject(object);
latest = new Node<VersionedObject>(vrObject);
}
, And here's my node class:
public class Node<T> {
private T data;
private Node next;
public Node() {
data = null;
next = null;
}
public Node(T data) {
this.data = data;
next = null;
}
public T getData() {
return data;
}
public Node<T> getNext() {
return next;
}
public void setData(T data) {
this.data = data;
}
public void setNext(Node<T> next) {
this.next = next;
}
@Override
public String toString() {
return data.toString();
}
}
Upvotes: 0
Views: 49
Reputation: 4859
Change the latest
to currentNode
and loop like this
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("key: " + key);
Node<VersionedObject> currNode = latest;
while (currNode != null){
builder.append(currNode + "\n\t");
currNode = currNode.getNext();
}
return builder.toString();
}
Upvotes: 2