开发者

How to compare generics of same type?

开发者 https://www.devze.com 2023-02-17 20:43 出处:网络
I\'m trying to compare two subclasses of Number inside a class with generics. In the code below, I\'m trying to compare Number objects inside an instance of Datum.

I'm trying to compare two subclasses of Number inside a class with generics. In the code below, I'm trying to compare Number objects inside an instance of Datum.

How do I enforce that both parameters passed to the Datum constructor are of the same class, so that I can compare what I know to be comparable types - e.g. Float and Float, or Long and 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开发者_如何学Python not compile

    }
}


You could restrict it to Comparable subclasses of Number:

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

  if (x.compareTo(y) > 0) { ... }
}


try

if (((Comparable)x).compareTo((Comparable)y)>0) {} 

instead of

if (x > y) {}


Compare the outcome of Number#doubleValue() instead.

if (x.doubleValue() > y.doubleValue()) {}


You could always compare the double values

return ((Double)x.doubleValue()).compareTo(y.doubleValue());
0

精彩评论

暂无评论...
验证码 换一张
取 消