我已經用一個類型變量創建了泛型類,它實現了java.lang.Comparable。我在如何實現compareTo()方法時遇到問題,因爲<>運算符不適用於泛型類型。我碰到這個對泛型的CompareTo方法的解釋
Create a compareTo to a Generic Class that Implements Comparable
來到遵循公認的答,我是能夠實現compareTo方法,但我不明白它是如何工作的,請任何人都可以解釋.... 答案我是指的是...
public class DoubleKey<K extends Comparable<K>, J extends Comparable<J>>
implements Comparable<DoubleKey<K, J>> {
private K key1;
private J key2;
public DoubleKey(K key1, J key2) {
this.key1 = key1;
this.key2 = key2;
}
public K getFirstKey() {
return this.key1;
}
public J getSecondKey() {
return this.key2;
}
public int compareTo(DoubleKey<K, J> that) {
int cmp = this.getFirstKey().compareTo(that.getFirstKey());
if (cmp == 0)
cmp = this.getSecondKey().compareTo(that.getSecondKey());
return cmp;
}
}
請張貼一些代碼。 – OldCurmudgeon
具體詢問你無法理解的內容! @ sky3287944! –
@shekharsuman在接受的答案我不明白以下內容:可比較是一個接口,所以如何來兩個泛型類型擴展它...也在執行compareTo()方法爲什麼它遞歸自己... .... – sky3287944