How to compare generics of the same type?

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

How to ensure that both parameters passed to the Datum constructor are of the same class, so I can compare what, as I know, with comparable types. 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 not compile } } 
+4
source share
4 answers

You can restrict it to Comparable subclasses of Number :

 class Datum<T extends Number & Comparable<? super T>> { ... if (x.compareTo(y) > 0) { ... } } 
+14
source

to try

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

instead

 if (x > y) {} 
+3
source

Compare the result of Number#doubleValue() .

 if (x.doubleValue() > y.doubleValue()) {} 
+1
source

You can always compare double values

 return ((Double)x.doubleValue()).compareTo(y.doubleValue()); 
+1
source

Source: https://habr.com/ru/post/1344523/


All Articles