Notice that several methods, such as synchronizedList( ) and synchronizedSet( ), are used
to obtain synchronized (thread-safe) copies of the various collections. As explained, none of
the standard collections implementations are synchronized. You must use the synchronization
algorithms to provide synchronization. One other point: iterators to synchronized collections
must be used within synchronized blocks.
The set of methods that begins with unmodifiable returns views of the various collections
that cannot be modified. These will be useful when you want to grant some process read--
but not write--capabilities on a collection.
Collections defines three static variables: EMPTY_SET, EMPTY_LIST, and EMPTY_MAP.
All are immutable.
The following program demonstrates some of the algorithms. It creates and initializes a
linked list. The reverseOrder( ) method returns a Comparator that reverses the comparison of
Integer objects. The list elements are sorted according to this comparator and then are displayed.
Next, the list is randomized by calling shuffle( ), and then its minimum and maximum values
are displayed.
// Demonstrate various algorithms.
import java.util.*;
class AlgorithmsDemo {
public static void main(String args[]) {
// Create and initialize linked list.
LinkedList<Integer> ll = new LinkedList<Integer>();
ll.add(-8);
ll.add(20);
ll.add(-20);
ll.add(8);
// Create a reverse order comparator.
Comparator<Integer> r = Collections.reverseOrder();
// Sort list by using the comparator.
Collections.sort(ll, r);
System.out.print("List sorted in reverse: ");
for(int i : ll)
System.out.print(i+ " ");
System.out.println();
// Shuffle list.
Collections.shuffle(ll);
// Display randomized list.
System.out.print("List shuffled: ");
for(int i : ll)
System.out.print(i + " ");
System.out.println();
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home