首页 > 解决方案 > 不兼容的类型会返回 statictype 的泛型方法

问题描述

我试图实现一个 BST 类就像

class BST<T> {
   private Node<T> root;
   private static class Node<T> {
     T element;
     Node<T> left;
     Node<T> right; 
   }  
}

我想在以 Node 作为参数并返回后继节点的方法中获取后继节点

private <T> Node<T> get(Node<T> current node){  
    Node<T> successor = root; 
}

在这里我得到不兼容的类型。如果我删除绑定的方法

private Node<T> get(Node<T> current node) {
    Node<T> successor = root;
}

现在它正在编译。是什么原因?

标签: javagenerics

解决方案


reason is T has already been defined at class level BST<T>. which means that you have to use BST<String>.method(); If you remove <T> from BST, the type will then have to be specified at the method level and you will need to add <T> at your method declaration. And calling the method will be BST.method<String>();


推荐阅读