Java comparing generic types

后端 未结 2 1269
萌比男神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.

提交回复
热议问题