Java Reference
In-Depth Information
Example 2•8: LinkedList.java (continued)
if (((LinkableInteger)o).i == this.i) return true;
return false;
}
}
/**
* The test program. Insert some nodes, remove some nodes, then
* print out all elements in the list. It should print out the
* numbers 4, 6, 3, 1, and 5
**/
public static void main(String[] args) {
LinkedList ll = new LinkedList(); // Create a list
ll.insertAtHead(new LinkableInteger(1)); // Insert some stuff
ll.insertAtHead(new LinkableInteger(2));
ll.insertAtHead(new LinkableInteger(3));
ll.insertAtHead(new LinkableInteger(4));
ll.insertAtTail(new LinkableInteger(5));
ll.insertAtTail(new LinkableInteger(6));
System.out.println(ll.removeFromHead()); // Remove and print a node
System.out.println(ll.removeFromTail()); // Remove and print again
ll.remove(new LinkableInteger(2));
// Remove another one
// Now print out the contents of the list.
for(Linkable l = ll.getHead(); l != null; l = l.getNext())
System.out.println(l);
}
}
}
Advanced Sorting
In Chapter 1, we saw an example of a simple, unsophisticated algorithm for sort-
ing an array of numbers. Example 2-9 defines a class,
Sorter
, that supports more
efficient and general-purpose sorting.
Sorter
defines a multitude of static
sort()
methods that each take slightly different arguments. A number of these methods
sort strings in various ways, while others sort other types of objects. The last of
these
sort()
methods implements the quicksort algorithm to efficiently sort an
array of objects. All other methods are variants; each one ultimately invokes the
general sorting method.
The
sort()
methods that sort strings take advantage of some of the international-
ization features introduced in Java 1.1. In particular, they use the
java.util.Locale
,
java.text.Collator
, and
java.text.CollationKey
classes. We
examine these classes in more detail in Chapter 7,
Inter nationalization
.
To sort an array of objects,
Sorter
needs some way to compare two objects to
determine which one should come before the other in the sorted array.
Sorter
defines two nested interfaces,
Sorter.Comparer
and
Sorter.Comparable
, that pro-
vide two different ways of implementing this comparison. You can sort arbitrary
objects by passing a
Comparer
object to one of the
sort()
methods. A
Comparer
object defines a
compare()
method that compares arbitrary objects. Alternatively,
the object classes you need to sort can implement the
Sorter.Comparable
inter-