代码之家  ›  专栏  ›  技术社区  ›  Faraz

绑定不匹配:类型不是该类型的有界参数<E>>的有效替代项

  •  0
  • Faraz  · 技术社区  · 4 年前

    我有一门课:

    public class BinarySearchTree<E extends Comparable<E>> {
        private TreeNode<E> root;
        //other methods like insert, etc
    }
    
    public class TreeNode<V extends Comparable<V>> implements Comparable<V>{
        //left and right instances of TreeNode and data holder V instance. 
        //insert method, etc
        @Override
        public int compareTo(V o) {
            return 0;
        }
    }
    

    当我在课堂上用 BinarySearchTree ,:

    public void levelOrderTraversalQueue() {
        Queue<TreeNode<E>> q = new Queue(); //<--Bound mismatch: The type BinarySearchTree<E>.TreeNode<E> is not a valid substitute for the bounded parameter <E extends Comparable<E>> of the type Queue<E>
    }
    

    为什么?我的队列类实现如下:

    public class Queue<E extends Comparable<E>> {
        private LinkedList<E> list;
        //other operations
    }
    

    如何解决此错误?

    1 回复  |  直到 4 年前
        1
  •  1
  •   Sweeper    4 年前

    这是:

    public class TreeNode<...> implements Comparable<V>{
    

    意味着 TreeNode V -它储存的东西。

    Queue ,树节点需要与 另一个树节点 . 召回:

    Queue<E extends Comparable<E>>
    

    E 是的,它必须实施 Comparable<E> 电子 TreeNode<V> .

    public class TreeNode<...> implements Comparable<TreeNode<V>> {