[英]How to compare generics of same type?
我正在嘗試將一個類中的兩個子類與泛型進行比較。 在下面的代碼中,我試圖比較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
}
}
您可以將其限制為Number
Comparable
子類:
class Datum<T extends Number & Comparable<? super T>> {
...
if (x.compareTo(y) > 0) { ... }
}
嘗試
if (((Comparable)x).compareTo((Comparable)y)>0) {}
代替
if (x > y) {}
比較Number#doubleValue()
的結果。
if (x.doubleValue() > y.doubleValue()) {}
您始終可以比較雙精度值
return ((Double)x.doubleValue()).compareTo(y.doubleValue());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.