2017-10-17 42 views
0

我现在有问题,试图用通用数据类型对二叉搜索树建模。我最终将读取字符串值并将它们插入二进制树中,因此Nodez类中的字符串声明。 Nodez类是我定义的用于声明节点传递给搜索树的类。字符串值将是该类的一个属性。 BSTree基于以下类定义:不兼容的类型:节点无法转换为Comparable(当作为参数传递时)

public class BSTree<E extends Comparable<E>> implements BSTreeAPI<E>  

我的问题在于主代码块。当我尝试插入Nodez类的一个实例时发生错误。这里的确切的错误说:“不兼容的类型:Nodez不能转换为可比”

我花了很多时间试图调试一个很好的数额,但我没有泛型如此之大?

有什么建议吗?谢谢!

package twotreesanalyzer; 
import java.io.IOException; 
import java.io.PrintStream; 
import java.util.function.Function; 

public class TwoTreesAnalyzer 
{ 

    public static class Nodez <E extends Comparable<E>> { 
     public String x; 
     public E node; 

     public String get(){ 
      return x; 
     } 
    } 

public static void main(String[] args) throws AVLTreeException, BSTreeException, IOException 
    {   

     Function<String, PrintStream> printUpperCase = x -> System.out.printf("%S", x); 

     BSTree bstTest = new BSTree(); 

     Nodez e1 = new Nodez(); 
     e1.x = "fresh"; 


     bstTest.insert(e1); 

     System.out.println(bstTest.inTree(e1.get())); 

    } 
} 
+0

以及如何类' Nodez'看起来像?它具有可比性吗?顺便说一下,为你的类/方法/对象提供好的名字是一个好主意,即使它只是一个玩具项目! – alfasin

+0

对。 Nodez被声明在main之上。当它实现了媲美,它返回一个指出nodez不是抽象的,在可比 – boppa

回答

1

现在你的BSTree试图比较你的nodez对象,如果这是你想要的功能,你需要在你的Nodez类上实现Comparible。我以集合树为例快速修复它。

public static class Nodez <E extends Comparable<E>> implements Comparable<Nodez<E>>{ 
     public String x; 
     public E node; 

     public String get(){ 
      return x; 
     } 

     @Override 
     public int compareTo(Nodez<E> node) { 
      return node.x.compareTo(x); 
     } 
    } 

public static void main(String[] args) throws IOException 
    {   

     Function<String, PrintStream> printUpperCase = x -> System.out.printf("%S", x); 

     TreeSet<Nodez<String>> bstTest = new TreeSet<>(); 

     Nodez<String> e1 = new Nodez<>(); 
     e1.x = "fresh"; 


     bstTest.add(e1); 

     System.out.println(bstTest.contains(e1)); 

    } 

不过我觉得你要为节点,能够接受任何泛型类型这可比在这种情况下,应责令更多像这样的位:

public static class Nodez <E extends Comparable<E>> implements Comparable<Nodez<E>>{ 
     public E x; 
     public Nodez<E> node; 

     public E get(){ 
      return x; 
     } 

     @Override 
     public int compareTo(Nodez<E> node) { 
      return node.x.compareTo(x); 
     } 
    } 

public static void main(String[] args) throws IOException 
    {   

     Function<String, PrintStream> printUpperCase = x -> System.out.printf("%S", x); 

     TreeSet<Nodez<String>> bstTest = new TreeSet<>(); 

     Nodez<String> e1 = new Nodez<>(); 
     e1.x = "fresh"; 


     bstTest.add(e1); 

     System.out.println(bstTest.contains(e1)); 
    } 
+0

愿望没有覆盖抽象方法的compareTo(E)我能给予好评这个100倍......这清除了这一切,但,是的,我会通过主要是字符串类型,但我仍然希望以更一般的方式对它进行建模。非常感谢你;像魅力一样工作 – boppa

+0

没问题,很高兴我能帮上忙。 – luckydog32

相关问题