nichi nichi - 3 months ago 12
Java Question

How to use compareTo() method to compare objects in a List?

I have a class called

ListNode
that works like a list. Using this class I want to establish a list of Magazine objects. In my
MagazineList
class I want to edit the add method so when I insert
Magazine
s they will be sorted alphabetically. How can I do this?

My
ListNode
class:

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;
}
}


my
MagazineList
class's add method:

//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);
}
}


I used this method to compare the
Magazines
in the
Magazine
class:

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

Answer

One easy way to do this is to keep your list always sorted.

Then, each time you insert a new node, starting from the head, you should compare the the new node with each node in the list using compareTo method, and insert the new node after the node for which compareTo returns positive.

A basic implementation may be like this. You need to improve it and consider edge cases etc. though.

//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);
   }
}