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!
str += temp.getString() + "";to add the space? Why or why not? Can you fix it? Then you'll only need to remove (or not add) the trailing space.StringBuilderand append the space before each item iff it is non-empty.new String(""+0). The expression"" + 0does already produce aString, which is by the way exactly the same as"0", passing this string into anew String(…)is obsolete. So just usel.add("0");,l.add("1");, andl.add("2");• The simplest approach is to useStringJoiner, e.g.StringJoiner j = new StringJoiner(" "); for(Node node = head; node != null; node = node.next) { j.add(node.getString()); } return j.toString();Or, to also get the square brackets replacenew StringJoiner(" ")withnew StringJoiner(" ", "[", "]")