我想做一個通用的方法來比較多種類型的對象。java調用一個通用的靜態方法
這是我簡單的接口
interface comparable<T> {
boolean isBiggerThan(T t1);
}
,這是它一個實現:
class StringComparable implements comparable<String> {
public StringComparable(String s) {
this.s = s;
}
String s;
@Override
public boolean isBiggerThan(String t1) {
return s.equals(t1);
}
}
這是我的類,它有一個通用的方法:
class Utilt {
public static <T extends comparable<T>> int biggerThan(T values[], T t) {
int count = 0;
for (T oneValue : values) {
if (oneValue.isBiggerThan(t)) {
count++;
}
}
return count;
}
}
我打電話像這樣的方法:
public class TestTest {
public static void main(String args[]) {
StringComparable a = new StringComparable("Totti");
StringComparable pi = new StringComparable("Pirlo");
int i = Utilt.biggerThan(new StringComparable[] { a, pi }, a);
}
}
但我得到這個錯誤:biggerThan
必須實現comparable<T>
您的靜態方法
The method `biggerThan(T[], T)` in the type `Utilt` is not applicable for the arguments `(StringComparable[], StringComparable)`
引用此:http://stackoverflow.com/questions/17739720/inferred-type-is-not-a-valid-substitute-for-a-comparable-generic-type – Boola