title: Implementation of toString() method in a linkedList
body: <p>I was trying to implement a method that prints out the contents inside a linked list.<br>
  Here is an explanation of classes that I use:    </p>
  
  <p>1) <code>NonEmptyListNode</code> and <code>EmptyListNode</code> inherit <code>AbstractListNode</code>.<br>
  2) a trailing node is represented with the <code>EmptyListNode</code>.  </p>
  
  <p>I actually implemented it, however, I felt bad since I was taught that <code>instanceof</code> keyword is bad. Here are my questions: </p>
  
  <p>1) Can I implement toString() without <code>instanceof</code> keyword?<br>
  2) Could I implement toString() in a recursive way?    </p>
  
  <p>Here is my code:  </p>
  
  <pre><code>abstract public class AbstractListNode {        
      abstract public Object item();
      abstract public AbstractListNode next();
      abstract public boolean isEmpty();
      abstract public int size();
      abstract public String toString();            
  }
  
  class NonemptyListNode extends AbstractListNode {
  
      private Object myItem;
      private AbstractListNode myNext;
  
      public NonemptyListNode (Object item, AbstractListNode next) {
          myItem = item;
          if (next == null) {
              myNext = new EmptyListNode();
          } else {
              myNext = next;
          }
      }
  
      public NonemptyListNode (Object item) {
          this (item, new EmptyListNode());
      }
  
      public Object item() { return myItem; }
  
      public AbstractListNode next() { return myNext; }
  
      public boolean isEmpty() {return false;}
  
      @Override
      public int size() {
          return 1 + myNext.size();
      }
  
      @Override
      public String toString() {
          AbstractListNode iter = this;
          String str = "( ";
  
          //HERE
          while(iter instanceof NonemptyListNode){
              str += iter.item() + " ";
              iter = iter.next();
          }
          return str + iter.toString();
      }
  }
  
  class EmptyListNode extends AbstractListNode {   
      public EmptyListNode() {}
  
      public Object item() {
          throw new IllegalArgumentException ("There is no 'item' value stored in an EmptyListNode.");
      }
  
      public AbstractListNode next() {
          throw new IllegalArgumentException ("No elements follow an EmptyListNode.");
      }
  
      public boolean isEmpty() {
          return true;
      }
  
      @Override
      public int size() {
          return 0;
      }
  
      @Override
      public String toString() {
          return ")";
      }
  }
  </code></pre>