title: Java Generic Casting Type Mismatch
body: <pre><code>public class MaxHeap&lt;T extends Comparable&lt;T&gt;&gt; implements Heap&lt;T&gt;{
  private T[] heap;
  private int lastIndex;
  
  public void main(String[] args){
      int i;
      T[] arr = {1,3,4,5,2}; //ERROR HERE *******
      foo
  }
  
  public T[] Heapsort(T[]anArray, int n){
      // build initial heap
      T[]sortedArray = anArray;
      for (int i = n-1; i&lt; 0; i--){
          //assert: the tree rooted at index is a semiheap
          heapRebuild(anArray, i, n);
          //assert: the tree rooted at index is a heap
      }
      //sort the heap array
      int last = n-1;
      //invariant: Array[0..last] is a heap,
      //Array[last+1..n-1] is sorted
      for (int j=1; j&lt;n-1;j++) {
          sortedArray[0]=sortedArray[last];
          last--;
          heapRebuild(anArray, 0, last);
      }
      return sortedArray;
  }
  
  protected void heapRebuild(T[ ] items, int root, int size){
  foo
  }
  
  }
  </code></pre>
  
  <p>The error is on the line with "<code>T[arr]  = {1,3,4,5,2}</code>"</p>
  
  <p>Eclipse complains that there is a:</p>
  
  <blockquote>
    <p>"Type mismatch: cannot convert from
    int to T"</p>
  </blockquote>
  
  <p>I've tried to casting nearly everywhere but to no avail.A simple way out would be to not use generics but instead just ints but that's sadly not an option. I've got to find a way to resolve the array of ints <code>{1,3,4,5,2}</code> into an array of T so that the rest of my code will work smoothly.</p>