THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

Any utility method that returns a collection will invariably be a generic method. We introduce the type
variable T to represent the unknown type of the collection being passed in. The snapshotIterator
method can accept any collection of T or a subtype of T, but only guarantees that it returns an
Iterator.[2]


[2] It is possible to return Iterator<? super T>, which is slightly more general than
Iterator<T>, but to do so would mean you wouldn't be able to assign the result to a
variable of type Iterator<T>. That would be a very annoying restriction.

Many of the iterators defined in the java.util package are what is known as fail-fast iterators. Such
iterators detect when a collection has been modified other than through the iterator itself, and fail quickly and
cleanly by throwing an exceptiona ConcurrentModificationExceptionrather than risk performing
an action whose behavior may be unsafe.


21.3. Ordering with Comparable and Comparator


The interface java.lang.Comparable can be implemented by any class whose objects can be
sorted. The interface has a single method:


public intcompareTo(T other)

Returns a value that is less than, equal to, or greater than zero as this object is
less than, equal to, or greater than the other object. This method should
return zero only if equals with the same object would return true. If the
objects are not mutually comparable (such as an Integer with a String),
a ClassCastException is thrown.

The ordering defined by compareTo is a class's natural ordering, that is, the ordering that is most natural to
objects of the class. It is also a total ordering, meaning that any two objects of the same type must be mutually
comparablethat is, you must be able to compare them in either order and always get the same result as to
which is the larger. Similarly, the equals method defines a natural equivalence.


Many existing classes are Comparable, including String, java.io.File, java.util.Date, and
all the primitive wrapper class types.


If a given class does not implement Comparable or if its natural ordering is wrong for some purpose, you
can often provide a java.util.Comparator object instead. The Comparator interface has the
method


public intcompare(T o1, T o2)

Provides an ordering in the same manner as Comparable.compareTo for
the two provided objects.

You can use Comparable and Comparator objects to sort and search List objects with the
Collections class's static methods sort and binarySearch. The Collections class (see page
594) also provides static methods min and max to return the smallest and largest element in a Collection.


Comparing strings ignoring case is a common requirement, so the String class defines a Comparator
object for this purpose, available from the field String.CASE_INSENSITIVE_ORDER.

Free download pdf