I think what I'm trying to do is clear, but I'm no Generics expert.
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);
}
}
I get a warning at compile-time:
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
which I don't understand. What am I missing?
I initially thought that it had to do with needing to check the that this.get(i) and this.get(parent) were instances of Comparable ... so I added a check:
if (!(this.get(i) instanceof Comparable) ||
!(this.get(parent) instanceof Comparable)) {
return false;
}
But that gives the same warning.
public class MinHeap<E extends Comparable> extends ArrayList<E>
should be
public class MinHeap<E extends Comparable<E>> extends ArrayList<E>
since Comparable
is a generic interface itself.