2013-09-25 21 views
1

我有一個名爲ListNode的類,其工作方式類似於列表。使用這個類我想建立一個雜誌對象列表。在我的MagazineList類中,我想編輯添加方法,因此當我插入Magazine時,它們將按字母順序排序。我怎樣才能做到這一點?如何使用compareTo()方法比較列表中的對象?

ListNode類:

public class ListNode { 
     private Object value; 
     private ListNode next; 

     //intializes node 
     public ListNode (Object initValue, ListNode initNext) { 
     value = initValue; 
     next = initNext; 
     } 

    //returns value of node 
    public Object getValue() { 
     return value; 
    } 

    //returns next reference of node 
    public ListNode getNext() { 
     return next; 
    } 

    //sets value of node 
    public void setValue (Object theNewValue) { 
     value = theNewValue; 
    } 

    //sets next reference of node 
    public void setNext (ListNode theNewNext) { 
     next = theNewNext; 
    } 
    } 

MagazineList類的add方法:

//when instantiated, MagazineList's list variable is set to null 
    public void add (Magazine mag) { 

     ListNode node = new ListNode (mag, null); 
     ListNode current; 

     if (list == null) 
     list = node; 
     else { 
     current = list; 
     while (current.getNext() != null) 
      current = current.getNext(); 
     current.setNext(node); 
     } 
    } 

我用這個方法將MagazinesMagazine類比較:

//compares the names (Strings) of the Magazines. 
    public int compareTo(Magazine mag2) { 
    return (title).compareTo(mag2.toString()); 
    } 

回答

1

這樣做的一個簡單方法是讓您的列表始終排序。然後,每次插入新節點時,從頭部開始,應使用compareTo方法將新節點與列表中的每個節點進行比較,並在compareTo返回正數的節點之後插入新節點。

一個基本的實現可能是這樣的。不過,你需要改進它並考慮邊緣案例等。

//when instantiated, MagazineList's list variable is set to null 
public void add (Magazine mag) { 

    ListNode node = new ListNode (mag, null); 
    ListNode current; 

    if (list == null) 
    list = node; 
    else { 
    current = list; // you list head 
    while (node.compareTo(current) < 0) 
     current = current.getNext(); 
    ListNode next = current.getNext(); 
    current.setNext(node); 
    node.setNext(next); 
    } 
} 
+0

感謝您的諮詢!我必須完成它與這個特定的實施,但是... – nichi

+0

我已更新回答使用您的實施。 – Mustafa

+0

非常感謝!你一直是一個偉大的幫助:) – nichi

1

篩選

//compares the names (Strings) of the Magazines. 
public int compareTo(Magazine mag2) { 
    //assume that you have getTittle() method which returns Title 
    return title.compareTo(mag2.getTitle()); 
} 
+0

這種方法與SO的不同之處在於如何提及。 –

+0

雖然我想在其他類的add()函數中使用compareTo()方法。我會怎麼做? – nichi