尝试在泛型类上实现可比较的接口时出现绑定不匹配错误



我正在为家庭作业创建一个自定义的PriorityQueue类,我遇到了一个障碍。我不知道如何修复我在Eclipse中得到的这个绑定不匹配错误;它不会让我尝试编译,因为它说:

有界不匹配:类型K不是Entry<K,V>类型的有界参数<K extends Comparable<K>>的有效替代

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.");
  }

}

您必须使K扩展Comparable也适用于PriorityQueue:

public class PriorityQueue<K extends Comparable<K>,V> {

实际上,泛型K将用于Entry<K,V>,并且Entry具有必须扩展(实际实现)Comparable<K>的约束。您必须告诉编译器PriorityQueue的K也满足此约束,因此它允许您使用Entry<K,V>

如果不是,有人可以使用不扩展Comparable的K的PriorityQueue,并且编译器必须检查K的所有使用,以查看是否没有阻止它使用的约束。

最新更新