I'm creating a toString() function that should return a String created by concatenating each Nodes toString(). A single space: ‘ ’ should be inserted between each Nodes toString(). No trailing space should be inserted.
For example, if the list contained 3 Node objects, the toString() return value would be [1 2 3], but not [123] or [1 2 3 ].
This is what I've tried so far and but it does not put a space between the elements (I get [01] when I need [0 1] for example):
public String toString() {
String str = "";
Node temp = head;
while (temp != null) {
str += temp.getString() + "";
temp = temp.next;
}
return str;
}
Here is the doubly linked list class I have with the add method:
public class DSEList {
public Node head;
private Node tail;
public DSEList() {
head = null;
tail = null;
}
public DSEList(Node head_) {
head = head_;
}
public boolean add(String obj) {
Node newNode = new Node(null, null, new String(obj));
Boolean success = false;
if(head == null) {
head = tail = newNode;
head.prev = null;
tail.next = null;
success = true;
}
else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
tail.next = null;
success = true;
}
return success;
}
Here is the node class I have where the getString() comes from:
public class Node {
public Node next;
public Node prev;
private String t;
public Node(Node next, Node prev, String token) {
this.next = next;
this.prev = prev;
this.t = token;
}
public String getString() {
return t;
}
@Override
public boolean equals(Object other) {
if (this == other)
return true;
if (other == null)
return false;
if (!(other instanceof Node))
return false;
return t.equals(((Node)other).getString());
}
@Override
public int hashCode() {
if ( t == null )
return 0;
return t.hashCode();
}
}
Here is an example of how it would work:
DSEList l = new DSEList();
l.add(new String(""+0));
l.toString() //this should return [0]
l.add(new String(""+1));
l.toString() //this should return [0 1]
l.add(new String(""+2));
l.toString() //this should return [0 1 2]
Thank you!
Use a StringJoiner
or a StringBuilder
rather than repeatedly appending strings in a loop. If using a StringBuilder
, prepend the space if and only if the StringBuilder
is non-empty.
Example with StringJoiner
:
@Override
public String toString() {
StringJoiner joiner = new StringJoiner(" ");
Node node = head;
while (node != null) {
joiner.append(node.getString());
node = node.next;
}
return joiner.toString();
}
Example with StringBuilder
:
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Node node = head;
while (node != null) {
if (!sb.isEmpty()) {
sb.append(' ');
}
sb.append(node.getString());
node = node.next;
}
return sb.toString();
}
Note: temp
is a terrible variable name for anything other than temp files and the intermediate value used in a swap.