通用二进制搜索树Java类型参数不在边界内

时间:2016-06-17 08:31:36

标签: java generics search

我做了以下二元搜索树,但它没有工作......需要帮助

class Tree<ContentType extends Comparable<ContentType>>{


  Node node;
  public Tree(){
    node = null;
  }
  public Tree(ContentType pContent){
    node = new Node<ContentType>(pContent);
  }
  public Tree(ContentType pContent, Tree pLeftTree, Tree pRightTree){
    node = new Node(pContent);
    node.setLeftTree(pLeftTree);
    node.setRightTree(pRightTree);
  }
  public boolean isEmpty(){
    ...
  }

  public void insert(ContentType pContent){
    ...
  } 

  public ContentType search(ContentType pContent){
    ...
  }

  public void delete(ContentType pContent){
    ...
  }
  public ContentType getContent(){
    ...
  }


...      

    private class Node<ContentType>{
        Tree left = null;
        Tree right = null;
        ContentType content = null;


        public Node(ContentType pContent){
          content=pContent;
          left = new Tree();
          right = new Tree();

        }

        ... 

    }


}

现在它告诉我

type-variable Content-Type#1 is not within bounds of type-variable Content-Type#2.

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

这里是完全修复的类文件 - 确保在声明类型的所有实例时指定泛型类型!

class Tree<ContentType extends Comparable<ContentType>>{

    // here
    Node<ContentType> node;

    public Tree(){
        node = null;
    }

    public Tree(ContentType pContent){
        node = new Node<ContentType>(pContent);
    }

    // each time Tree is used, it should be typed!
    public Tree(ContentType pContent, Tree<ContentType> pLeftTree, Tree<ContentType> pRightTree){
        // same with Node!
        node = new Node<ContentType>(pContent);
        node.setLeftTree(pLeftTree);
        node.setRightTree(pRightTree);
    }

    //Node needs to be typed with the exact same type as Tree!
    private class Node<ContentType extends Comparable<ContentType>>{
        // Typed Tree!
        Tree<ContentType> left = null;
        Tree<ContentType> right = null;
        ContentType content = null;


        public Node(ContentType pContent){
            content=pContent;
            left = new Tree<ContentType>();
            right = new Tree<ContentType>(); 
        }

        public void setLeftTree(Tree<ContentType> tree) {
            left = tree;
        }

        public void setRightTree(Tree<ContentType> tree) {
            right = tree;
        }
    }
}

编译无警告:

~ bfung$ javac -version
javac 1.8.0_40
~ bfung$ javac Tree.java
~ bfung$