【发布时间】:2013-09-25 05:35:36
【问题描述】:
我有一个名为ListNode 的类,它的作用类似于一个列表。使用这个类,我想建立一个杂志对象列表。在我的 MagazineList 类中,我想编辑 add 方法,因此当我插入 Magazines 时,它们将按字母顺序排序。我怎样才能做到这一点?
我的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);
}
}
我用这个方法比较了Magazine类中的Magazines:
//compares the names (Strings) of the Magazines.
public int compareTo(Magazine mag2) {
return (title).compareTo(mag2.toString());
}
【问题讨论】: