Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Notice that several methods, such assynchronizedList( )andsynchronizedSet( ), 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 withinsynchronizedblocks.
The set of methods that begins withunmodifiablereturns 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.
Collectionsdefines three static variables:EMPTY_SET,EMPTY_LIST, andEMPTY_MAP.
All are immutable.
The following program demonstrates some of the algorithms. It creates and initializes a
linked list. ThereverseOrder( )method returns aComparatorthat reverses the comparison of
Integerobjects. The list elements are sorted accordingto thiscomparator and then are displayed.
Next, the list is randomized by callingshuffle( ), 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();

Chapter 17: java.util Part 1: The Collections Framework 479

Free download pdf