Look at
this thread, where Johnathan Smith is trying to compare players in a team by batting average. Also Johnathan Smith's earlier posting on the same subject.
Look up the
Comparable <T>interface, and work out how to implement it, with the compareTo(T t) method in your Grocery class. Note that String already implements Comparable, so comparing Strings is already set up and ready to use.
Look up the Java Tutorial about
Collections. The bit about how sorting is done appears under
"algorithms." It is easier to sort an ArrayList than a LinkedList. If you have a doubly-linked list it is easier.
More about sorting algorithms
here, and it gives an example of how to implement the algorithms for arrays. The code given is in C but
you should be able to translate it into Java in a minute or so.
You need to work out a "swap" routine for LinkedLists. Remember all "swap" routines need three members, first, second and temp, of the three kinds.
Assuming your LinkedList has a reference to "next" for "next member," try this sort of thing.
Create a "temp" Member.Set "temp" equal to "next"Set "this.next" equal to "next.next"set "next.next" equal to "temp"Move to the next memberIf the next member is null stop, otherwise repeat. I think I have written that correctly You will notice from Lamont's explanations that the simple sort algorithms require two loops through your collection.
If you have a few things to sort, by all means use bubble sort, even though merge sort and quicksort are much faster. As Lamont says, for 100 members bubble and merge work about the same speed; for 10 members bubble is faster because it is simpler, and for 1000 members merge and quick are faster because they require fewer comparisons.
If you get a NullPointerException you might have hit a null at the end of your list earlier than you thought.
BTW: Everybody calls what Lamont describes bubble sort, but the pedants call it sinking sort; bubble sort is exactly the same but you count backwards.