Index (Frames) | Index (No Frames) | Package | Package Tree | Tree
java.util

Class Collections

java.lang.Object
|
+--java.util.Collections


public class Collections

extends Object

Utility class consisting of static methods that operate on, or return Collections. Contains methods to sort, search, reverse, fill and shuffle Collections, methods to facilitate interoperability with legacy APIs that are unaware of collections, a method to return a list which consists of multiple copies of one element, and methods which "wrap" collections to give them extra properties, such as thread-safety and unmodifiability.

All methods which take a collection throw a NullPointerException if that collection is null. Algorithms which can change a collection may, but are not required, to throw the UnsupportedOperationException that the underlying collection would throw during an attempt at modification. For example, Collections.singleton("").addAll(Collections.EMPTY_SET) does not throw a exception, even though addAll is an unsupported operation on a singleton; the reason for this is that addAll did not attempt to modify the set.

Since:Authors:See Also:

Field Summary

static java.util.ListEMPTY_LIST

An immutable, serializable, empty List, which implements RandomAccess.
static java.util.MapEMPTY_MAP

An immutable, serializable, empty Map.
static java.util.SetEMPTY_SET

An immutable, serializable, empty Set.

Method Summary

static intbinarySearch(java.util.List l, java.lang.Object key)

Perform a binary search of a List for a key, using the natural ordering of the elements.
static intbinarySearch(java.util.List l, java.lang.Object key, java.util.Comparator c)

Perform a binary search of a List for a key, using a supplied Comparator.
static voidcopy(java.util.List dest, java.util.List source)

Copy one list to another.
static java.util.Enumerationenumeration(java.util.Collection c)

Returns an Enumeration over a collection.
static voidfill(java.util.List l, java.lang.Object val)

Replace every element of a list with a given value.
static intindexOfSubList(java.util.List source, java.util.List target)

Returns the starting index where the specified sublist first occurs in a larger list, or -1 if there is no matching position.
static intlastIndexOfSubList(java.util.List source, java.util.List target)

Returns the starting index where the specified sublist last occurs in a larger list, or -1 if there is no matching position.
static java.util.ArrayListlist(java.util.Enumeration e)

Returns an ArrayList holding the elements visited by a given Enumeration.
static java.lang.Objectmax(java.util.Collection c)

Find the maximum element in a Collection, according to the natural ordering of the elements.
static java.lang.Objectmax(java.util.Collection c, java.util.Comparator order)

Find the maximum element in a Collection, according to a specified Comparator.
static java.lang.Objectmin(java.util.Collection c)

Find the minimum element in a Collection, according to the natural ordering of the elements.
static java.lang.Objectmin(java.util.Collection c, java.util.Comparator order)

Find the minimum element in a Collection, according to a specified Comparator.
static java.util.ListnCopies(final int n, final Object o)

Creates an immutable list consisting of the same object repeated n times.
static booleanreplaceAll(java.util.List list, java.lang.Object oldval, java.lang.Object newval)

Replace all instances of one object with another in the specified list.
static voidreverse(java.util.List l)

Reverse a given list.
static java.util.ComparatorreverseOrder()

Get a comparator that implements the reverse of natural ordering.
static voidrotate(java.util.List list, int distance)

Rotate the elements in a list by a specified distance.
static voidshuffle(java.util.List l)

Shuffle a list according to a default source of randomness.
static voidshuffle(java.util.List l, java.util.Random r)

Shuffle a list according to a given source of randomness.
static java.util.Setsingleton(java.lang.Object o)

Obtain an immutable Set consisting of a single element.
static java.util.ListsingletonList(java.lang.Object o)

Obtain an immutable List consisting of a single element.
static java.util.MapsingletonMap(java.lang.Object key, java.lang.Object value)

Obtain an immutable Map consisting of a single key-value pair.
static voidsort(java.util.List l)

Sort a list according to the natural ordering of its elements.
static voidsort(java.util.List l, java.util.Comparator c)

Sort a list according to a specified Comparator.
static voidswap(java.util.List l, int i, int j)

Swaps the elements at the specified positions within the list.
static java.util.CollectionsynchronizedCollection(java.util.Collection c)

Returns a synchronized (thread-safe) collection wrapper backed by the given collection.
static java.util.ListsynchronizedList(java.util.List l)

Returns a synchronized (thread-safe) list wrapper backed by the given list.
static java.util.MapsynchronizedMap(java.util.Map m)

Returns a synchronized (thread-safe) map wrapper backed by the given map.
static java.util.SetsynchronizedSet(java.util.Set s)

Returns a synchronized (thread-safe) set wrapper backed by the given set.
static java.util.SortedMapsynchronizedSortedMap(java.util.SortedMap m)

Returns a synchronized (thread-safe) sorted map wrapper backed by the given map.
static java.util.SortedSetsynchronizedSortedSet(java.util.SortedSet s)

Returns a synchronized (thread-safe) sorted set wrapper backed by the given set.
static java.util.CollectionunmodifiableCollection(java.util.Collection c)

Returns an unmodifiable view of the given collection.
static java.util.ListunmodifiableList(java.util.List l)

Returns an unmodifiable view of the given list.
static java.util.MapunmodifiableMap(java.util.Map m)

Returns an unmodifiable view of the given map.
static java.util.SetunmodifiableSet(java.util.Set s)

Returns an unmodifiable view of the given set.
static java.util.SortedMapunmodifiableSortedMap(java.util.SortedMap m)

Returns an unmodifiable view of the given sorted map.
static java.util.SortedSetunmodifiableSortedSet(java.util.SortedSet s)

Returns an unmodifiable view of the given sorted set.

Field Details

EMPTY_LIST

public static final List EMPTY_LIST

An immutable, serializable, empty List, which implements RandomAccess.

See Also:


EMPTY_MAP

public static final Map EMPTY_MAP

An immutable, serializable, empty Map.

See Also:


EMPTY_SET

public static final Set EMPTY_SET

An immutable, serializable, empty Set.

See Also:


Method Details

binarySearch

public static int binarySearch(java.util.List l, java.lang.Object key)

Perform a binary search of a List for a key, using the natural ordering of the elements. The list must be sorted (as by the sort() method) - if it is not, the behavior of this method is undefined, and may be an infinite loop. Further, the key must be comparable with every item in the list. If the list contains the key more than once, any one of them may be found.

This algorithm behaves in log(n) time for RandomAccess lists, and uses a linear search with O(n) link traversals and log(n) comparisons with AbstractSequentialList lists. Note: although the specification allows for an infinite loop if the list is unsorted, it will not happen in this (Classpath) implementation.

Parameters:

Returns:

Throws:

See Also:


binarySearch

public static int binarySearch(java.util.List l, java.lang.Object key, java.util.Comparator c)

Perform a binary search of a List for a key, using a supplied Comparator. The list must be sorted (as by the sort() method with the same Comparator) - if it is not, the behavior of this method is undefined, and may be an infinite loop. Further, the key must be comparable with every item in the list. If the list contains the key more than once, any one of them may be found. If the comparator is null, the elements' natural ordering is used.

This algorithm behaves in log(n) time for RandomAccess lists, and uses a linear search with O(n) link traversals and log(n) comparisons with AbstractSequentialList lists. Note: although the specification allows for an infinite loop if the list is unsorted, it will not happen in this (Classpath) implementation.

Parameters:

Returns:

Throws:

See Also:


copy

public static void copy(java.util.List dest, java.util.List source)

Copy one list to another. If the destination list is longer than the source list, the remaining elements are unaffected. This method runs in linear time.

Parameters:

Throws:


enumeration

public static Enumeration enumeration(java.util.Collection c)

Returns an Enumeration over a collection. This allows interoperability with legacy APIs that require an Enumeration as input.

Parameters:

Returns:


fill

public static void fill(java.util.List l, java.lang.Object val)

Replace every element of a list with a given value. This method runs in linear time.

Parameters:

Throws:


indexOfSubList

public static int indexOfSubList(java.util.List source, java.util.List target)

Returns the starting index where the specified sublist first occurs in a larger list, or -1 if there is no matching position. If target.size() > source.size(), this returns -1, otherwise this implementation uses brute force, checking for source.sublist(i, i + target.size()).equals(target) for all possible i.

Since:Parameters:

Returns:


lastIndexOfSubList

public static int lastIndexOfSubList(java.util.List source, java.util.List target)

Returns the starting index where the specified sublist last occurs in a larger list, or -1 if there is no matching position. If target.size() > source.size(), this returns -1, otherwise this implementation uses brute force, checking for source.sublist(i, i + target.size()).equals(target) for all possible i.

Since:Parameters:

Returns:


list

public static ArrayList list(java.util.Enumeration e)

Returns an ArrayList holding the elements visited by a given Enumeration. This method exists for interoperability between legacy APIs and the new Collection API.

Since:Parameters:

Returns:

See Also:


max

public static Object max(java.util.Collection c)

Find the maximum element in a Collection, according to the natural ordering of the elements. This implementation iterates over the Collection, so it works in linear time.

Parameters:

Returns:

Throws:


max

public static Object max(java.util.Collection c, java.util.Comparator order)

Find the maximum element in a Collection, according to a specified Comparator. This implementation iterates over the Collection, so it works in linear time.

Parameters:

Returns:

Throws:


min

public static Object min(java.util.Collection c)

Find the minimum element in a Collection, according to the natural ordering of the elements. This implementation iterates over the Collection, so it works in linear time.

Parameters:

Returns:

Throws:


min

public static Object min(java.util.Collection c, java.util.Comparator order)

Find the minimum element in a Collection, according to a specified Comparator. This implementation iterates over the Collection, so it works in linear time.

Parameters:

Returns:

Throws:


nCopies

public static List nCopies(final int n, final Object o)

Creates an immutable list consisting of the same object repeated n times. The returned object is tiny, consisting of only a single reference to the object and a count of the number of elements. It is Serializable, and implements RandomAccess. You can use it in tandem with List.addAll for fast list construction.

Parameters:

Returns:

Throws:

See Also:


replaceAll

public static boolean replaceAll(java.util.List list, java.lang.Object oldval, java.lang.Object newval)

Replace all instances of one object with another in the specified list. The list does not change size. An element e is replaced if oldval == null ? e == null : oldval.equals(e).

Since:Parameters:

Returns:

Throws:


reverse

public static void reverse(java.util.List l)

Reverse a given list. This method works in linear time.

Parameters:

Throws:


reverseOrder

public static Comparator reverseOrder()

Get a comparator that implements the reverse of natural ordering. In other words, this sorts Comparable objects opposite of how their compareTo method would sort. This makes it easy to sort into reverse order, by simply passing Collections.reverseOrder() to the sort method. The return value of this method is Serializable.

Returns:

See Also:


rotate

public static void rotate(java.util.List list, int distance)

Rotate the elements in a list by a specified distance. After calling this method, the element now at index i was formerly at index (i - distance) mod list.size(). The list size is unchanged.

For example, suppose a list contains [t, a, n, k, s]. After either Collections.rotate(l, 4) or Collections.rotate(l, -1), the new contents are [s, t, a, n, k]. This can be applied to sublists to rotate just a portion of the list. For example, to move element a forward two positions in the original example, use Collections.rotate(l.subList(1, 3+1), -1), which will result in [t, n, k, a, s].

If the list is small or implements RandomAccess, the implementation exchanges the first element to its destination, then the displaced element, and so on until a circuit has been completed. The process is repeated if needed on the second element, and so forth, until all elements have been swapped. For large non-random lists, the implementation breaks the list into two sublists at index -distance mod size, calls #reverse(List) on the pieces, then reverses the overall list.

Since:Parameters:

Throws:


shuffle

public static void shuffle(java.util.List l)

Shuffle a list according to a default source of randomness. The algorithm used iterates backwards over the list, swapping each element with an element randomly selected from the elements in positions less than or equal to it (using r.nextInt(int)).

This algorithm would result in a perfectly fair shuffle (that is, each element would have an equal chance of ending up in any position) if r were a perfect source of randomness. In practice the results are merely very close to perfect.

This method operates in linear time. To do this on large lists which do not implement RandomAccess, a temporary array is used to acheive this speed, since it would be quadratic access otherwise.

Parameters:

Throws:


shuffle

public static void shuffle(java.util.List l, java.util.Random r)

Shuffle a list according to a given source of randomness. The algorithm used iterates backwards over the list, swapping each element with an element randomly selected from the elements in positions less than or equal to it (using r.nextInt(int)).

This algorithm would result in a perfectly fair shuffle (that is, each element would have an equal chance of ending up in any position) if r were a perfect source of randomness. In practise (eg if r = new Random()) the results are merely very close to perfect.

This method operates in linear time. To do this on large lists which do not implement RandomAccess, a temporary array is used to acheive this speed, since it would be quadratic access otherwise.

Parameters:

Throws:


singleton

public static Set singleton(java.lang.Object o)

Obtain an immutable Set consisting of a single element. The return value of this method is Serializable.

Parameters:

Returns:

See Also:


singletonList

public static List singletonList(java.lang.Object o)

Obtain an immutable List consisting of a single element. The return value of this method is Serializable, and implements RandomAccess.

Since:Parameters:

Returns:

See Also:


singletonMap

public static Map singletonMap(java.lang.Object key, java.lang.Object value)

Obtain an immutable Map consisting of a single key-value pair. The return value of this method is Serializable.

Since:Parameters:

Returns:

See Also:


sort

public static void sort(java.util.List l)

Sort a list according to the natural ordering of its elements. The list must be modifiable, but can be of fixed size. The sort algorithm is precisely that used by Arrays.sort(Object[]), which offers guaranteed nlog(n) performance. This implementation dumps the list into an array, sorts the array, and then iterates over the list setting each element from the array.

Parameters:

Throws:

See Also:


sort

public static void sort(java.util.List l, java.util.Comparator c)

Sort a list according to a specified Comparator. The list must be modifiable, but can be of fixed size. The sort algorithm is precisely that used by Arrays.sort(Object[], Comparator), which offers guaranteed nlog(n) performance. This implementation dumps the list into an array, sorts the array, and then iterates over the list setting each element from the array.

Parameters:

Throws:

See Also:


swap

public static void swap(java.util.List l, int i, int j)

Swaps the elements at the specified positions within the list. Equal positions have no effect.

Since:Parameters:

Throws:


synchronizedCollection

public static Collection synchronizedCollection(java.util.Collection c)

Returns a synchronized (thread-safe) collection wrapper backed by the given collection. Notice that element access through the iterators is thread-safe, but if the collection can be structurally modified (adding or removing elements) then you should synchronize around the iteration to avoid non-deterministic behavior:
 Collection c = Collections.synchronizedCollection(new Collection(...));
 ...
 synchronized (c)
   {
     Iterator i = c.iterator();
     while (i.hasNext())
       foo(i.next());
   }
 

Since the collection might be a List or a Set, and those have incompatible equals and hashCode requirements, this relies on Object's implementation rather than passing those calls on to the wrapped collection. The returned Collection implements Serializable, but can only be serialized if the collection it wraps is likewise Serializable.

Parameters:

Returns:

See Also:


synchronizedList

public static List synchronizedList(java.util.List l)

Returns a synchronized (thread-safe) list wrapper backed by the given list. Notice that element access through the iterators is thread-safe, but if the list can be structurally modified (adding or removing elements) then you should synchronize around the iteration to avoid non-deterministic behavior:
 List l = Collections.synchronizedList(new List(...));
 ...
 synchronized (l)
   {
     Iterator i = l.iterator();
     while (i.hasNext())
       foo(i.next());
   }
 

The returned List implements Serializable, but can only be serialized if the list it wraps is likewise Serializable. In addition, if the wrapped list implements RandomAccess, this does too.

Parameters:

Returns:

See Also:


synchronizedMap

public static Map synchronizedMap(java.util.Map m)

Returns a synchronized (thread-safe) map wrapper backed by the given map. Notice that element access through the collection views and their iterators are thread-safe, but if the map can be structurally modified (adding or removing elements) then you should synchronize around the iteration to avoid non-deterministic behavior:
 Map m = Collections.synchronizedMap(new Map(...));
 ...
 Set s = m.keySet(); // safe outside a synchronized block
 synchronized (m) // synch on m, not s
   {
     Iterator i = s.iterator();
     while (i.hasNext())
       foo(i.next());
   }
 

The returned Map implements Serializable, but can only be serialized if the map it wraps is likewise Serializable.

Parameters:

Returns:

See Also:


synchronizedSet

public static Set synchronizedSet(java.util.Set s)

Returns a synchronized (thread-safe) set wrapper backed by the given set. Notice that element access through the iterator is thread-safe, but if the set can be structurally modified (adding or removing elements) then you should synchronize around the iteration to avoid non-deterministic behavior:
 Set s = Collections.synchronizedSet(new Set(...));
 ...
 synchronized (s)
   {
     Iterator i = s.iterator();
     while (i.hasNext())
       foo(i.next());
   }
 

The returned Set implements Serializable, but can only be serialized if the set it wraps is likewise Serializable.

Parameters:

Returns:

See Also:


synchronizedSortedMap

public static SortedMap synchronizedSortedMap(java.util.SortedMap m)

Returns a synchronized (thread-safe) sorted map wrapper backed by the given map. Notice that element access through the collection views, subviews, and their iterators are thread-safe, but if the map can be structurally modified (adding or removing elements) then you should synchronize around the iteration to avoid non-deterministic behavior:
 SortedMap m = Collections.synchronizedSortedMap(new SortedMap(...));
 ...
 Set s = m.keySet(); // safe outside a synchronized block
 SortedMap m2 = m.headMap(foo); // safe outside a synchronized block
 Set s2 = m2.keySet(); // safe outside a synchronized block
 synchronized (m) // synch on m, not m2, s or s2
   {
     Iterator i = s.iterator();
     while (i.hasNext())
       foo(i.next());
     i = s2.iterator();
     while (i.hasNext())
       bar(i.next());
   }
 

The returned SortedMap implements Serializable, but can only be serialized if the map it wraps is likewise Serializable.

Parameters:

Returns:

See Also:


synchronizedSortedSet

public static SortedSet synchronizedSortedSet(java.util.SortedSet s)

Returns a synchronized (thread-safe) sorted set wrapper backed by the given set. Notice that element access through the iterator and through subviews are thread-safe, but if the set can be structurally modified (adding or removing elements) then you should synchronize around the iteration to avoid non-deterministic behavior:
 SortedSet s = Collections.synchronizedSortedSet(new SortedSet(...));
 ...
 SortedSet s2 = s.headSet(foo); // safe outside a synchronized block
 synchronized (s) // synch on s, not s2
   {
     Iterator i = s2.iterator();
     while (i.hasNext())
       foo(i.next());
   }
 

The returned SortedSet implements Serializable, but can only be serialized if the set it wraps is likewise Serializable.

Parameters:

Returns:

See Also:


unmodifiableCollection

public static Collection unmodifiableCollection(java.util.Collection c)

Returns an unmodifiable view of the given collection. This allows "read-only" access, although changes in the backing collection show up in this view. Attempts to modify the collection directly or via iterators will fail with UnsupportedOperationException.

Since the collection might be a List or a Set, and those have incompatible equals and hashCode requirements, this relies on Object's implementation rather than passing those calls on to the wrapped collection. The returned Collection implements Serializable, but can only be serialized if the collection it wraps is likewise Serializable.

Parameters:

Returns:

See Also:


unmodifiableList

public static List unmodifiableList(java.util.List l)

Returns an unmodifiable view of the given list. This allows "read-only" access, although changes in the backing list show up in this view. Attempts to modify the list directly, via iterators, or via sublists, will fail with UnsupportedOperationException.

The returned List implements Serializable, but can only be serialized if the list it wraps is likewise Serializable. In addition, if the wrapped list implements RandomAccess, this does too.

Parameters:

Returns:

See Also:


unmodifiableMap

public static Map unmodifiableMap(java.util.Map m)

Returns an unmodifiable view of the given map. This allows "read-only" access, although changes in the backing map show up in this view. Attempts to modify the map directly, or via collection views or their iterators will fail with UnsupportedOperationException.

The returned Map implements Serializable, but can only be serialized if the map it wraps is likewise Serializable.

Parameters:

Returns:

See Also:


unmodifiableSet

public static Set unmodifiableSet(java.util.Set s)

Returns an unmodifiable view of the given set. This allows "read-only" access, although changes in the backing set show up in this view. Attempts to modify the set directly or via iterators will fail with UnsupportedOperationException.

The returned Set implements Serializable, but can only be serialized if the set it wraps is likewise Serializable.

Parameters:

Returns:

See Also:


unmodifiableSortedMap

public static SortedMap unmodifiableSortedMap(java.util.SortedMap m)

Returns an unmodifiable view of the given sorted map. This allows "read-only" access, although changes in the backing map show up in this view. Attempts to modify the map directly, via subviews, via collection views, or iterators, will fail with UnsupportedOperationException.

The returned SortedMap implements Serializable, but can only be serialized if the map it wraps is likewise Serializable.

Parameters:

Returns:

See Also:


unmodifiableSortedSet

public static SortedSet unmodifiableSortedSet(java.util.SortedSet s)

Returns an unmodifiable view of the given sorted set. This allows "read-only" access, although changes in the backing set show up in this view. Attempts to modify the set directly, via subsets, or via iterators, will fail with UnsupportedOperationException.

The returns SortedSet implements Serializable, but can only be serialized if the set it wraps is likewise Serializable.

Parameters:

Returns:

See Also: