我有一個名爲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);
}
}
我用這個方法將Magazines
在Magazine
類比較:
//compares the names (Strings) of the Magazines.
public int compareTo(Magazine mag2) {
return (title).compareTo(mag2.toString());
}
感謝您的諮詢!我必須完成它與這個特定的實施,但是... – nichi
我已更新回答使用您的實施。 – Mustafa
非常感謝!你一直是一個偉大的幫助:) – nichi