我正在为家庭作业制作一个自定义的PriorityQueue课程,而且我遇到了障碍。我无法弄清楚如何解决我在Eclipse中遇到的Bound Mismatch错误;它不会让我尝试编译,因为它说:
绑定不匹配:类型
K
不能替代<K extends Comparable<K>>
类型的有界参数Entry<K,V>
PriorityQueue.java:
public class PriorityQueue<K,V> {
private Entry<K,V> _head;
private Entry<K,V> _tail;
private int _size;
public PriorityQueue() {
this._head = null;
this._tail = null;
this._size = 0;
}
public int size() {
return _size;
}
public boolean isEmpty() {
return (size() == 0);
}
public Entry<K,V> min() {
if (_head == null) {
return null;
}
Entry<K,V> current = _head;
Entry<K,V> min = _head;;
while (current != null) {
if (current.compareTo(min) < 0) {
min = current;
}
current = current.getNext();
}
return min;
}
public Entry<K,V> insert(K k, V x) {
Entry<K,V> temp = new Entry<K,V>(k,x);
if (_tail == null) {
_tail = temp;
_head = temp;
}
else {
_tail.setNext(temp);
temp.setPrev(_tail);
_tail = temp;
}
return temp;
}
public Entry<K,V> removeMin() {
Entry<K,V> smallest = min();
smallest.getPrev().setNext(smallest.getNext());
smallest.getNext().setPrev(smallest.getPrev());
return smallest;
}
public String toString() {
return null;
}
public static void main(String[] args) {
PriorityQueue<Integer, Integer> pq =
new PriorityQueue<Integer, Integer>();
pq.insert(4, 2);
pq.insert(5, 1);
pq.insert(1, 5);
System.out.println(pq.min().toString());
}
}
Entry.java:
public class Entry<K extends Comparable<K>,V> implements Comparable<Entry<K,V>> {
private V _value;
private K _key;
private Entry<K,V> _prev;
private Entry<K,V> _next;
public Entry(K key, V value) {
this._value = value;
this._key = key;
this._prev = null;
this._next = null;
}
public V getValue() {
return this._value;
}
public K getKey() {
return this._key;
}
public Entry<K,V> getNext() {
return _next;
}
public void setNext(Entry<K,V> link) {
this._next = link;
}
public Entry<K,V> getPrev() {
return _prev;
}
public void setPrev(Entry<K,V> link) {
this._prev = link;
}
public String toString() {
return "" + this.getValue();
}
@Override
public int compareTo(Entry<K,V> o) {
if (o instanceof Entry<?,?>) {
return this.getKey().compareTo(o.getKey());
}
throw new IllegalArgumentException("Objects are not comparable.");
}
}
答案 0 :(得分:3)
您必须使K Comparable
PriorityQueue
延伸public class PriorityQueue<K extends Comparable<K>,V> {
:
Entry<K,V>
实际上,泛型类型K将用于Comparable<K>
,而Entry具有必须扩展(实际实现)Entry<K,V>
的约束。您必须告诉编译器,PriorityQueue的K也满足此约束,因此它允许您使用{{1}}。
如果没有,有人可以使用不会扩展Comparable的K的PriorityQueue,并且编译器必须检查K的所有使用,以查看是否没有阻止它使用的约束。