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 not compile
}
}
You could restrict it to
Comparablesubclasses ofNumber: