[英]How to compare primitives with Java Generics?
我正在學習Java泛型。 我想使用無界泛型來比較基元。我有以下代碼,
public static <T extends Comparable<T>> T max(T x, T y) {
return x > y ? x : y;
}
但不會編譯。 錯誤是:
The operator > is undefined for the argument type(s) T
要比較兩個Comparable
對象, 必須使用compareTo
,這里是x.compareTo(y)
。 您的方法可以寫
return x.compareTo(y) > 0 ? x : y;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.