title: java-linked list sublist method
body: <p>I am attempting to write a subList method, which returns a list consisting of the current object list inclusively between indexes <code>fromIndex</code> and <code>toIndex</code>.</p>
  
  <p>For example, if I had list consisting of</p>
  
  <blockquote>
    <p>9 11 20 23 28 30</p>
  </blockquote>
  
  <p>and I called <code>subList(1,4)</code>, I should get a new list of </p>
  
  <blockquote>
    <p>11 20 23 28</p>
  </blockquote>
  
  <p>returned.</p>
  
  <p>For my subList() method, I tried running it but I end up entering an infinite loop. When the next node is empty, it is supposed to exit the loop but that is not happening so I need help figuring out why this infinite loop is happening and what I can do about it. Any help is appreciated!</p>
  
  <pre><code>private class Node&lt;N extends Comparable&lt;N&gt;&gt; {
      private N data;
      private Node&lt;N&gt; next;
  }
  
  private Node&lt;L&gt; head;
  
  public List() {
      head = null;
  }   
  
  private void add(Node&lt;L&gt; node) {
          if(head == null) {
              head=node;
          } else {
              getFinal().next = node;
          }
      }
  
  public Node&lt;L&gt; getFinal(){
      Node&lt;L&gt; node = head;
      while (node.next != null) {
          node = node.next;
      }
      return node;
  }
  
  public int size() {
      if (head == null) return 0;
      int counter = 0;
      for (Node&lt;L&gt; curr = head; curr != null; curr = curr.next)
          counter++;
      return counter;
  }
  
  public List&lt;L&gt; subList(int fromIndex, int toIndex) throws IndexOutOfBoundsException {
      if(fromIndex &lt; 0 || fromIndex &gt; size()-1 || toIndex &lt; 0 || toIndex &gt; size()-1) { 
           throw new IndexOutOfBoundsException();
      }
  
      List&lt;L&gt; n = new List&lt;L&gt;();
      Node&lt;L&gt; startNode = head;
      int counter = 0;
      while(startNode != null) {
          if(counter &gt;= fromIndex &amp;&amp; counter &lt;= toIndex) { //infinite loop happens here
              n.add(startNode);
          }
          startNode=startNode.next;
          counter++;
      }
  
      return n;
  }
  </code></pre>