2012-07-26 62 views
1

我應該在我的insert -method上簽名?我正在努力與泛型。在某種程度上,我想要Comparable<T>T,並且我嘗試過<Comparable<T> extends T>如何在Java中編寫「實現Comparable <T>」的方法簽名?

public class Node<T> { 

    private Comparable<T> value; 

    public Node(Comparable<T> val) { 
     this.value = val; 
    } 

    // WRONG signature - compareTo need an argument of type T 
    public void insert(Comparable<T> val) { 
     if(value.compareTo(val) > 0) { 
      new Node<T>(val); 
     } 
    } 

    public static void main(String[] args) { 
     Integer i4 = new Integer(4); 
     Integer i7 = new Integer(7); 

     Node<Integer> n4 = new Node<>(i4); 
     n4.insert(i7); 
    } 
} 
+0

爲什麼你要比較2'Comparator'的? – 2012-07-26 12:03:42

+0

@ TheEliteGentleman我想比較兩個'Comparable',所以我可以按照順序排列它們。 – Jonas 2012-07-26 12:06:41

回答

6

不知道你想什麼來實現,但你不應該包含在類的聲明?

public static class Node<T extends Comparable<T>> { //HERE 

    private T value; 

    public Node(T val) { 
     this.value = val; 
    } 

    public void insert(T val) { 
     if (value.compareTo(val) > 0) { 
      new Node<T>(val); 
     } 
    } 
} 

注:這是很好的做法是使用<T extends Comparable<? super T>>代替<T extends Comparable<T>>

+2

爲獲得最佳效果,請使用'>' – newacct 2012-07-26 18:23:35

+0

@newacct您是對的 - 我已經做了相應的編輯。 – assylias 2012-07-26 19:44:56

相關問題