title: How to find the size of a generic singly-linked list in java
body: <p>I am having trouble finding out the size of a generic singly-linked list in java. Here is my code (below I will explain how I tried to find it out and what difficulties I encountered):</p>
  
  <pre><code>class List&lt;T&gt; {
  /**
   * An immutable singly-linked list.
   * @param &lt;T&gt; the type of the list elements
   */
  T head;
  List&lt;T&gt; tail;
  
  List(T head, List&lt;T&gt; tail) {
      this.head = head;
      this.tail = tail;
  }
  
  /** Generic helper function for list creation. You DO NOT NEED to call this function. */
  static &lt;U&gt; List&lt;U&gt; node(U head, List&lt;U&gt; tail) {
      return new List&lt;U&gt;(head, tail);
  }
  
  
  /* Getters and Setters for the head and the tail; */
  public List&lt;T&gt; getTail() {
      return tail;
  }
  
  public void setTail(List&lt;T&gt; tail) {
      this.tail = tail;
  }
  
  public T getHead() {
      return head;
  }
  
  public void setHead(T head) {
      this.head = head;
  }
  </code></pre>
  
  <p>I tried to find out the size like this:
  loop through the elements of the linked list, beninning with the first element, until the "next" pointer shows <code>null</code>. increment the helper variable <code>size</code>.
  Code:</p>
  
  <pre><code>    public int size(){
      int size = 0;
  
      T temp = head;
      while (temp.getTail() != null) {
          temp = temp.getTail();
          size++;
      }
  
      return size;
  }
  </code></pre>
  
  <p>The problem is <code>temp.getTail()</code>. Eclipse is asking in this specific case to cast the variable <code>temp</code> to <code>List&lt;T&gt;</code>. But this makes for me no sense, hence <code>List&lt;T&gt;</code> should be just like a "next" pointer to the next element of the list.</p>
  
  <p>Could somebody please be so kind and explin what I'm doing wrong and how I could solve this. I am really trying to understand generics (I also read a lot about generics but still can't seem to figure out how to handle this kind of situation).</p>
  
  <p>I will use this list in my test class:</p>
  
  <pre><code>        List&lt;Integer&gt; coins = List.node(1, List.node(2, List.node(5,  List.node(10,
              List.node(20, List.node(50, List.node(100,  List.node(200, null))))))));
  </code></pre>
  
  <p>I will recursively calculate the number of possible coin combinations (the values 1, 2, 5, 10, 20, 50, 100 and 200) given an EURO amount.</p>