![](/img/trans.png)
[英]How to extend Generic abstract Class with <E extends Comparable<E>>
[英]How do I subclass ArrayList, and require that <E> must extend Comparable
我认为我想做的事情很明确,但我不是泛型专家。
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;
}
但这给出了同样的警告。
public class MinHeap<E extends Comparable> extends ArrayList<E>
应该
public class MinHeap<E extends Comparable<E>> extends ArrayList<E>
因为Comparable
本身就是通用接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.