title: Java Implementing linkedlist public <T> T[] toArray(T[] a)
body: <p>I'm writing my own implementation of a double linked list.</p>
  
  <p>I got to method <code>public &lt;T&gt; T[] toArray(T[] a)</code></p>
  
  <pre><code>public &lt;T&gt; T[] toArray(T[] a) {
  
      if (a.length &lt; size()) {
          T[] array = (T[]) new Object[size()];
  
          Node temp = head;
  
          int currentIndex = 0;
  
          while (currentIndex &lt; size) {
              a[currentIndex] = (T) temp.data;
              currentIndex++;
              temp = temp.next;
          }
      }
  
      if (a.length &gt; size()) {
          a[size] = null;         
      }
  
      Node temp = head;
      for (int i = 0; i &lt; size; i++) {
          a[i] = (T) temp.data;
          temp = temp.next;
      }
  
      return a;
  }
  </code></pre>
  
  <p>I am testing it with</p>
  
  <pre><code>    List&lt;String&gt; list = new DoubleLinkedList&lt;String&gt;();
  
      list.add(0, ("0"));
      list.add(1, ("1"));
      list.add(2, ("2"));
      list.add(3, ("3"));
      list.add(4, ("4"));
      list.add(5, ("5"));
  
      String array[] = list.toArray(new String[6]);
  
      for (int i = 0; i &lt; list.size(); i++) {
          System.out.println(array[i]);
      }
  </code></pre>
  
  <p>It works when I test it with <code>String array[] = list.toArray(new String[6]);</code> or <code>String array[] = list.toArray(new String[7]);</code> or any number higher. But nothing prints out if I test with <code>String array[] = list.toArray(new String[5]);</code> or below. JUnit throws a ClassCastException.</p>
  
  <p>Please help me figure this out.</p>
  
  <p>Edit1: changed some irrelevant code.</p>