Printing out a linked list using toString
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertFront(1);
list.insertFront(2);
list.insertFront(3);
System.out.println(list.toString());
}
String toString() {
String result = "";
LinkedListNode current = head;
while(current.getNext() != null){
result += current.getData();
if(current.getNext() != null){
result += ", ";
}
current = current.getNext();
}
return "List: " + result;
}
As has been pointed out in some other answers and comments, what you are missing here is a call to the JVM System class to print out the string generated by your toString() method.
LinkedList myLinkedList = new LinkedList();
System.out.println(myLinkedList.toString());
This will get the job done, but I wouldn't recommend doing it that way. If we take a look at the javadocs for the Object class, we find this description for toString():
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The emphasis added there is my own. You are creating a string that contains the entire state of the linked list, which somebody using your class is probably not expecting. I would recommend the following changes:
- Add a toString() method to your LinkedListNode class.
- Update the toString() method in your LinkedList class to be more concise.
- Add a new method called printList() to your LinkedList class that does what you are currently expecting toString() to do.
In LinkedListNode:
public String toString(){
return "LinkedListNode with data: " + getData();
}
In LinkedList:
public int size(){
int currentSize = 0;
LinkedListNode current = head;
while(current != null){
currentSize = currentSize + 1;
current = current.getNext();
}
return currentSize;
}
public String toString(){
return "LinkedList with " + size() + "elements.";
}
public void printList(){
System.out.println("Contents of " + toString());
LinkedListNode current = head;
while(current != null){
System.out.println(current.toString());
current = current.getNext();
}
}