我有一个名为的类ListNode
,它就像一个列表。使用这个类,我想建立一个杂志对象列表。在我的MagazineList
课堂上,我想编辑 add 方法,因此当我插入Magazine
s 时,它们将按字母顺序排序。我怎样才能做到这一点?
我的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());
}