如何比较相同类型的泛型?

4 java generics compare

我正在尝试将一个类中的两个子类与泛型进行比较.在下面的代码中,我试图比较Datum实例中的Number对象.

如何强制传递给Datum构造函数的两个参数属于同一个类,以便我可以比较我所知道的可比类型 - 例如Float和Float,或Long和Long?

Float f1 = new Float(1.5);
Float f2 = new Float(2.5);

new Datum<Number>(f1, f2);

class Datum<T extends Number> {
    T x;
    T y;

Datum(T xNum, T yNum) {

    x = xNum;
    y = yNum;
            if (x > y) {} // does not compile

    }
}
Run Code Online (Sandbox Code Playgroud)

Col*_*inD 14

您可以将其限制为以下Comparable子类Number:

class Datum<T extends Number & Comparable<? super T>> {
  ...

  if (x.compareTo(y) > 0) { ... }
}
Run Code Online (Sandbox Code Playgroud)