478 Part II: The Java Library
Several of the methods can throw aClassCastException, which occurs when an attempt
is made to compare incompatible types, or anUnsupportedOperationException, which occurs
when an attempt is made to modify an unmodifiable collection. Other exceptions are
possible, depending on the method.
One thing to pay special attention to is the set ofcheckedmethods, such as
checkedCollection( ), which returns what the API documentation refers to as a “dynamically
typesafe view” of a collection. This view is a reference to the collection that monitors insertions
into the collection for type compatibility at run time. An attempt to insert an incompatible
element will cause aClassCastException. Using such a view is especially helpful during
debugging because it ensures that the collection always contains valid elements. Related
methods includecheckedSet( ),checkedList( ),checkedMap( ), and so on. They obtain a
type-safe view for the indicated collection.
Method Description
static <T>
void sor t(List<T>list,
Comparator<? super T>comp)
Sor ts the elements oflistas determined bycomp.
static <T extends Comparable<? super T>>
void sor t(List<T>list)
Sor ts the elements oflistas determined by their
natural ordering.
static void swap(List<?>list,
intidx1, intidx2)
Exchanges the elements inlistat the indices
specified byidx1andidx2.
static <T> Collection<T>
synchronizedCollection(Collection<T>c)
Returns a thread-safe collection backed byc.
static <T> List<T> synchronizedList(List<T>list) Returns a thread-safe list backed bylist.
static <K, V> Map<K, V>
synchronizedMap(Map<K, V>m)
Returns a thread-safe map backed bym.
static <T> Set<T> synchronizedSet(Set<T>s) Returns a thread-safe set backed bys.
static <K, V> Sor tedMap<K, V>
synchronizedSor tedMap(Sor tedMap<K, V>sm)
Returns a thread-safe sor ted map backed bysm.
static <T> Sor tedSet<T>
synchronizedSor tedSet(Sor tedSet<T>ss)
Returns a thread-safe set backed byss.
static <T> Collection<T>
unmodifiableCollection(
Collection<? extends T>c)
Returns an unmodifiable collection backed byc.
static <T> List<T>
unmodifiableList(List<? extends T>list)
Returns an unmodifiable list backed bylist.
static <K, V> Map<K, V>
unmodifiableMap(Map<? extends K,
? extends V>m)
Returns an unmodifiable map backed bym.
static <T> Set<T>
unmodifiableSet(Set<? extends T>s)
Returns an unmodifiable set backed bys.
static <K, V> Sor tedMap<K, V>
unmodifiableSor tedMap(Sor tedMap<K,
? extends V>sm)
Returns an unmodifiable sor ted map backed
bysm.
static <T> Sor tedSet<T>
unmodifiableSor tedSet(Sor tedSet<T>ss)
Returns an unmodifiable sor ted set backed byss.
TABLE 17-14 The Algorithms Defined byCollections(continued)