The Collections Helper Class

As we mentioned above, there is a “helper” class that contains about 50 static methods and nested classes that operate on or return a Collection. Here's the API for that class Collections, simplified to omit generic parameters.

We'll first show the class, then look at generic parameters in more detail.

public class Collections extends Object {
    public static final Set EMPTY_SET;
    public static final List EMPTY_LIST;
    public static final Map EMPTY_MAP;

    public static void sort(List);
    public static void sort(List, Comparator);
    public static int binarySearch(List, Object);
    public static int iteratorBinarySearch(List, Object);
    public static int binarySearch(List, Object, Comparator);
    public static int iteratorBinarySearch(List, Object, Comparator);
    public static void reverse(List);
    public static void shuffle(List);
    public static void shuffle(List, Random);
    public static void swap(List, int, int);
    public static void fill(List, Object);
    public static void copy(List, List);
    public static void rotate(List, int);
    public static boolean replaceAll(List, Object, Object);
    public static int indexOfSubList(List, List);
    public static int lastIndexOfSubList(List, List);
    public static List nCopies(int, Object);
    public static List list(Enumeration);

    public static Object min(Collection);
    public static Object min(Collection, Comparator);
    public static Object max(Collection);
    public static Object max(Collection, Comparator);
    public static Collection synchronizedCollection(Collection);

    public static Set synchronizedSet(Set);
    public static SortedSet synchronizedSortedSet(SortedSet);
    public static List synchronizedList(List);
    public static Map synchronizedMap(Map);
    public static SortedMap synchronizedSortedMap(SortedMap);

    public static Set singleton(Object);
    public static List singletonList(Object);
    public static Map singletonMap(Object, Object);
    public static Comparator reverseOrder();
    public static Enumeration enumeration(Collection);
}

About half of the methods provide further List operations, including sorting and searching. These operations are not needed for Sets because there is a subtype of Set that is defined to be held in sorted order. The API documentation has the full description of each of these methods.

One useful thing is to sort a List into order. The helper class java.util.Collections contains a static method that sorts a List. Here's an example List of String.

LinkedList <String> cs = new LinkedList<String>();
// code to add elements
cs.add( "data" );
cs.add( "element" );
cs.add( "boolean" );
cs.add( "computer" );
cs.add( "algorithm" );

Here's the one-liner (excellent!) to sort that list:

Collections.sort( cs );
System.out.println("lexicographic order: " + cs );

Here's how to compile and run the code:

% javac -source 1.5 example.java
% java example
lexicographic order: [algorithm, boolean, computer, data, element]

Comparable and Comparator

You might wonder how the Collections class is able to sort a List: how does it know how elements are compared with each other? The answer is that you tell it. You tell Collections or anyone who is interested how objects-of-your-class-in-a-collection are ordered by implementing one of two available interfaces:

  • java.lang.Comparable –. Implement this interface when there is a single obvious natural ordering for the objects.

    public interface java.lang.Comparable<T> {
        public int compareTo( T rhs);
    }

    We described this generic interface in the previous chapter. String implements Comparable, with a natural ordering of alphabetic. They call it “lexicographic order,” rather than “alphabetic order,” because lots of string values are digits, punctuation, or other non-alphabetic characters.

  • java.util.Comparator –. Implement this generic interface when there are several equally good orderings for the objects. Create one Comparator for each ordering you want to offer.

    public interface java.util.Comparator <T> {
        public int compare(T lhs, T rhs);
        public boolean equals(Object comp);
    }

    The compare() method returns a negative, zero, or positive int, for <, equal, > exactly like Comparable's compareTo().

    The equals() method is a tricky one. It is used to check two Comparators (not the objects they are comparing) to see if they are the same. If the Comparators are the same, and your List is already in the order of one of them, you don't need to sort it again. Usually you leave this method out and let your Comparator inherit the equals() method from Object.

Any class implementing one of these interfaces must be very careful to keep the normal mathematical properties expected of comparisons. If a equals b, and b equals c, then it is expected that a equals c. Further, a should equal a, and the method should be consistent with its own or any parent object's equal() method. The API documentation has a lengthy discussion of this topic.

The class java.lang.String has a Comparator, as well as implementing Comparable. The Comparator is implemented as a static nested class that is private inside the String class, and which does a comparison ignoring letter case.

private static class CaseInsensitiveComparator
                   implements Comparator, java.io.Serializable {
        public int compare(Object o1, Object o2) {
          // 20 lines of code, omitted
        }
}

Then, also inside String, the Comparator is instantiated and made publicly available as part of String's API:

public static final Comparator CASE_INSENSITIVE_ORDER
                                   = new CaseInsensitiveComparator();

The point of that is that String exports one case insensitive comparator, and you cannot declare your own copies, or extend String's one.

It's time to present the final piece of generics, and we'll use the class java.util.Collections as our example in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.234.24