-3

When I call toString(), it's calling the built-in toString() and not my custom version.

Here is my code (with unnecessary code removed to make this more of a minimal, complete, verifiable question:

public class DoublyLinkedList<Item extends Comparable> {

    private class Node{
      private Item item;
      private Node next;
      private Node prev;
      //methods to get/set next, prev, item
    }

    private Node head;
    private int numberOfEelements;

    //methods to add/remove items (sorted)

    public String toString(){
      Node current = head;
      StringBuilder sb = new StringBuilder();
      while(current != null){
        sb.append(current).append("Item: " + " ");
        current = current.getNext();
      }
      return sb.toString();
    }

    public static void main(String[] args) {

       DoublyLinkedList<Integer> list = new DoublyLinkedList<Integer>();
        list.sortedAdd(1);
        list.sortedAdd(5);
        list.sortedAdd(7);
        list.sortedAdd(9);
        list.sortedAdd(3);
        list.sortedAdd(2);
        list.sortedRemove(3);
        System.out.println(list.toString());

    }
}

Any help would be really appreciated. Thanks.

Foon
  • 6,148
  • 11
  • 40
  • 42
Toni
  • 31
  • 1
  • 6

1 Answers1

3

Replace

list.toString();

with

System.out.println(list.toString());

Explanation: The toString method generates a String representation of an object, but it does not generate any output. So you have to send the result to e.g. System.out.

fabian
  • 80,457
  • 12
  • 86
  • 114
Jan
  • 2,060
  • 2
  • 29
  • 34
  • i tried this bro, it prints something like this DoublyLinkedList$Node@3cd1a2f1Item: – Toni Aug 10 '15 at 16:03
  • Yes, because that is the default String representation of any object: The name of the class and the address in memory. There are many ways to create a more meaningful output. For example you can overwrite `toString` in your `DoublyLinkedList` to iterate over the entries and create a more meaningful output by some kind of concatenation. – Jan Aug 10 '15 at 16:07
  • @Toni: That's because you're using [`Object.toString`](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#toString--) of your `Node`s. (You did not override `toString` for `Node`). Add the **content** of the nodes to the `String`, not the `Node`s. – fabian Aug 10 '15 at 16:09
  • but how should i iterate over the list. i never used iterators? :p – Toni Aug 10 '15 at 16:10