【发布时间】:2021-08-12 22:55:43
【问题描述】:
我想实现一个基于数组的堆。然而,这个堆应该可以用一个数组来调用,要么只包含实现 Comparable 接口的元素,要么用一个额外的 Comparator (因此,如果没有给出 Comparator,则假定每个元素都可以相互比较)。然后我想检查它的有效性。它不起作用,因为无法调用扩展 Comparable 的 heapCondition。
public class Heap <T>{
Object[] tree;
Comparator<T> comparator;
public <T extends Comparable<T>> Heap(T[] tree){
this.tree = tree;
}
public Heap(T[] tree, Comparator<T> 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 <T extends Comparable<T>> boolean heapCondition(T parent, T child){
return parent.compareTo(child) < 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) < 0;
}
/**
* @return boolean whether or not the current tree fulfills the Heap condition
*
*/
private boolean valid(){
for(int i = 0; 2*i+2 < 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;
}
}
【问题讨论】:
标签: java arrays generics heap comparable