我认为我想做的很清楚,但我不是泛型专家。
import java.util.ArrayList;
public class MinHeap<E extends Comparable> extends ArrayList<E> {
/* A simple wrapper around a List to make it a binary min-heap. */
public MinHeap() {
super();
}
@Override
public boolean add(E e) {
super.add(e);
int i = this.size() - 1;
int parent;
while (i > 0) {
parent = this.getParentIndex(i);
if (this.get(i).compareTo(this.get(parent)) < 0) {
this.swap(i, parent);
} else {
break;
}
}
return true;
}
public int getParentIndex(int i) {
if (i % 2 == 1) {
return (i - 1) / 2;
} else {
return (i - 2) / 2;
}
}
private void swap(int i, int j) {
E temp = this.get(i);
this.set(i, this.get(j));
this.set(j, temp);
}
}
我在编译时收到警告:
MinHeap.java:21: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type Comparable
if (this.get(i).compareTo(this.get(parent)) < 0) {
^
where T is a type-variable:
T extends Object declared in interface Comparable
1 warning
我不明白。我错过了什么?
我最初认为这与需要检查 this.get(i) 和 this.get(parent) 是 Comparable 的实例有关......所以我添加了一个检查:
if (!(this.get(i) instanceof Comparable) ||
!(this.get(parent) instanceof Comparable)) {
return false;
}
但这给出了同样的警告。