title: Implement Heap with generics in Java
body: <p>I want to implement a Heap based on an Array. However, this Heap is should be callable with an Array of either only elements that implement the Comparable interface or with an additional Comparator (so if no Comparator is given it is assumed every element can be compareTo with one another). Then I want to check for its validity. It doesn't work because the heapCondition for extends Comparable can not be called.</p>
  <pre><code>public class Heap &lt;T&gt;{
  Object[] tree;
  Comparator&lt;T&gt; comparator;
  
  public &lt;T extends Comparable&lt;T&gt;&gt; Heap(T[] tree){
      this.tree = tree;
  }
  
  public Heap(T[] tree, Comparator&lt;T&gt; comparator){
      this.tree = tree;
      this.comparator = comparator;
  }
  
  /**
   * defines the heapCondition default is set so the Heap is a minHeap (parent is smaller than their children)
   * @param parent parent node
   * @param child child node
   */
  public &lt;T extends Comparable&lt;T&gt;&gt; boolean heapCondition(T parent, T child){
      return parent.compareTo(child) &lt; 0;
  }
  
  public boolean heapCondition(T parent, T child){
      if(comparator == null){
          // go into the heap condition where to Comparable is assumed
          heapCondition(parent,child);
      }
      return comparator.compare(parent,child) &lt; 0;
  }
  
  
  /**
   * @return boolean whether or not the current tree fulfills the Heap condition
   *
   */
  private boolean valid(){
      for(int i = 0; 2*i+2 &lt; tree.length; i++){
          // returns false if the condition is not met for one of the children
          return !(!heapCondition((T) tree[i], (T) tree[2*i+1]) || !heapCondition((T) tree[i],(T) tree[2*i+2]));
      }
      return true;
  }
  }
  </code></pre>