Java comparing generic types

后端 未结 2 1256
萌比男神i
萌比男神i 2020-12-05 14:15

In Java, I wrote a Binary Search Tree class that adds nodes using recursion. Now I want to generalize it using Generics so I can learn more about them.

publi         


        
相关标签:
2条回答
  • 2020-12-05 14:33

    You cannot overload operators in Java. The < operator only applies to primitive (or numeric) types, not reference types. Since T is a type variable that represents a reference type, you cannot use < on variables of type T. You have to use

    if (item.compareTo(bn.item) < 0) 
    

    check the value returned and decide to do what you wish with it.

    You don't know what the type T will be but you know that it will be a type that implements Comparable and therefore implements the compareTo() method.

    0 讨论(0)
  • 2020-12-05 14:59

    You can use this simple approach
    for data greater than root.getData = 1, for data equals root.getData = 0,for data lesser than root.getData = -1

    public class BST<E extends Number & Comparable<? super E>>{
        void add(){
        ...
        if(data.compareTo(root.getData()) == 1)
        ...
    }
    
    0 讨论(0)
提交回复
热议问题