我有一个名为 ListNode
的类,它的工作方式类似于列表。我想使用这个类建立杂志对象的列表。在我的 MagazineList
类中,我想编辑 add 方法,这样当我插入 Magazine
时,它们将按字母顺序排序。我怎样才能做到这一点?
我的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
类中的Magazine
:
//compares the names (Strings) of the Magazines.
public int compareTo(Magazine mag2) {
return (title).compareTo(mag2.toString());
}
最佳答案
实现此目的的一个简单方法是始终保持列表有序。
然后,每次插入新节点时,从头部开始,使用 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);
}
}
关于java - 如何使用compareTo()方法比较List中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18997004/