Porównywalny i porównawczy interfejs w Javie
Chcę napisać ogólną klasę par, która ma dwa elementy: klucz i wartość. Jedynym wymogiem tej klasy jest to, że zarówno klucz, jak i wartość powinny implementować interfejs Comparable, w przeciwnym razie klasa Pair nie zaakceptuje ich jako parametru typu.
Najpierw koduję to tak:
public class Pair<T1 extends Comparable, T2 extends Comparable>
Ale kompilator JDK 1.6 wygeneruje ostrzeżenie o tym:
Comparable is a raw type. References to generic type Comparable<T> should be parameterized
Następnie próbowałem dodać parametry typu i kod wygląda teraz tak:
public class Pair<T1 extends Comparable<? extends Object>,
T2 extends Comparable<? extends Object>>
Teraz wszystko idzie dobrze, dopóki nie próbowałem wygenerować komparatora dla pary (poniższy kod jest w klasie par)
public final Comparator<Pair<T1, T2>> KEY_COMPARATOR = new Comparator<Pair<T1, T2>>() {
public int compare(Pair<T1, T2> first, Pair<T1, T2> second) {
*first.getKey().compareTo(second.getKey());*
return 0;
}
};
Kodfirst.getKey().compareTo(second.getKey());
wygeneruje błąd mówiący:
The method compareTo(capture#1-of ? extends Object) in the type Comparable<capture#1-of ? extends Object> is not applicable for the arguments (T1)
Ktoś wie, co oznacza ten komunikat o błędzie?
Wszelkie wskazówki na ten temat są mile widziane.
AKTUALIZACJA:
Oto pełny kod:
public class Pair<T1 extends Comparable<? extends Object>, T2 extends Comparable<? extends Object>> {
private T1 key;
private T2 value;
public static int ascending = 1;
public final Comparator<Pair<T1, T2>> KEY_COMPARATOR = new Comparator<Pair<T1, T2>>() {
public int compare(Pair<T1, T2> first, Pair<T1, T2> second) {
int cmp = first.getKey().compareTo((T1)(second.getKey()));
if (cmp > 0) return ascending;
return -ascending;
}
};
}
@MarvinLabs Czy możesz wyjaśnić nieco więcej, dlaczego kompilator nie może upewnić się, że obiekty są porównywane z innymi obiektami tego samego typu. W powyższym kodziesecond.getKey()
zwraca typ T1, który jest tego samego typu cofirst.getKey()