title: Using Generic in LinkedList that implements Iterable
body: <p>I want to understand under what circumstances Generics should be used.</p>
  
  <p>Suppose that I want to implement a LinkedList that is iterable. Obviously, the LinkedList should have type parameter that are generic:</p>
  
  <p>Implementation 1:</p>
  
  <pre><code>public class LinkedList&lt;E&gt;{
      private Node head;
  
      private class Node{
          private Node next;
          private E e;
      }
  }
  </code></pre>
  
  <p>My first question: should Node also have type parameter E? That is, should the above code be written as:</p>
  
  <p>Implementation 2:</p>
  
  <pre><code>public class LinkedList&lt;E&gt;{
      private Node&lt;E&gt; head;
  
      private class Node&lt;E&gt;{
          private Node&lt;E&gt; next;
          private E e;
      }
  }
  </code></pre>
  
  <p>Both implementations compile fine. I have seen implementation 1 in a textbook of mine. Therefore, it seems like implementation 2 is a little unnecessary.</p>
  
  <p>Next, I want to implement Iterable. Suppose we stick with Implementation 1, we will have:</p>
  
  <p>Implementation 3:</p>
  
  <pre><code>public class LinkedList&lt;E&gt; implements Iterable&lt;E&gt;{
  private Node head;
  
  private class Node{
      private Node next;
      private E e;
  }
  
  public Iterator&lt;E&gt; iterator(){
      return new LinkedListIterator();
  }
  
  private class LinkedListIterator implements Iterator&lt;E&gt;{
      private Node curr;
  
      public boolean hasNext(){
          return curr != null;
      }
      public E next(){
          E element = curr.e;
          curr = curr.next;
          return element;
      }
  }    
  </code></pre>
  
  <p>This is the standard kind of implementation that I have seen in textbooks.</p>
  
  <p>My second question: since we do not have generic type for Node, why can't we not use generic type for the Iterable and Iterator as well? e.g.:</p>
  
  <p>Implementation 4:</p>
  
  <pre><code>public class LinkedList1&lt;E&gt; implements Iterable{
      private Node head;
  
      private class Node{
          private Node next;
          private E e;
      }
  
      public Iterator iterator(){
          return new LinkedListIterator();
      }
  
      private class LinkedListIterator implements Iterator{
          private Node curr = head;
  
          public boolean hasNext(){
              return curr != null;
          }
          public E next(){
              E element = curr.e;
              curr = curr.next;
              return element;
          }
      }    
  }
  </code></pre>