我正在为家庭作业制作自定义 PriorityQueue 类,但遇到了障碍。我不知道如何解决我在 Eclipse 中遇到的这个 Bound Mismatch 错误;它不会让我尝试编译,因为它说:
有界不匹配:该类型
K
不是该类型的有界参数<K extends Comparable<K>>
的有效替代品Entry<K,V>
优先队列.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());
}
}
入口.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.");
}
}