[英]How do I subclass ArrayList, and require that <E> must extend Comparable
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: 我最初认为这与需要检查this.get(i)和this.get(parent)是Comparable的实例有关...因此我添加了一个检查:
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. 因为
Comparable
本身就是通用接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.