public class Collections extends Object
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.
Collection
,
Set
,
List
,
Map
,
Arrays
Modifier and Type | Field and Description |
---|---|
static List |
EMPTY_LIST
An immutable, serializable, empty List, which implements RandomAccess.
|
static Map |
EMPTY_MAP
An immutable, serializable, empty Map.
|
static Set |
EMPTY_SET
An immutable, serializable, empty Set.
|
Modifier and Type | Method and Description |
---|---|
static int |
binarySearch(List l,
Object key)
Perform a binary search of a List for a key, using the natural ordering of
the elements.
|
static int |
binarySearch(List l,
Object key,
Comparator c)
Perform a binary search of a List for a key, using a supplied Comparator.
|
static void |
copy(List dest,
List source)
Copy one list to another.
|
static Enumeration |
enumeration(Collection c)
Returns an Enumeration over a collection.
|
static void |
fill(List l,
Object val)
Replace every element of a list with a given value.
|
static int |
indexOfSubList(List source,
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 int |
lastIndexOfSubList(List source,
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 ArrayList |
list(Enumeration e)
Returns an ArrayList holding the elements visited by a given
Enumeration.
|
static Object |
max(Collection c)
Find the maximum element in a Collection, according to the natural
ordering of the elements.
|
static Object |
max(Collection c,
Comparator order)
Find the maximum element in a Collection, according to a specified
Comparator.
|
static Object |
min(Collection c)
Find the minimum element in a Collection, according to the natural
ordering of the elements.
|
static Object |
min(Collection c,
Comparator order)
Find the minimum element in a Collection, according to a specified
Comparator.
|
static List |
nCopies(int n,
Object o)
Creates an immutable list consisting of the same object repeated n times.
|
static boolean |
replaceAll(List list,
Object oldval,
Object newval)
Replace all instances of one object with another in the specified list.
|
static void |
reverse(List l)
Reverse a given list.
|
static Comparator |
reverseOrder()
Get a comparator that implements the reverse of natural ordering.
|
static void |
rotate(List list,
int distance)
Rotate the elements in a list by a specified distance.
|
static void |
shuffle(List l)
Shuffle a list according to a default source of randomness.
|
static void |
shuffle(List l,
Random r)
Shuffle a list according to a given source of randomness.
|
static Set |
singleton(Object o)
Obtain an immutable Set consisting of a single element.
|
static List |
singletonList(Object o)
Obtain an immutable List consisting of a single element.
|
static Map |
singletonMap(Object key,
Object value)
Obtain an immutable Map consisting of a single key-value pair.
|
static void |
sort(List l)
Sort a list according to the natural ordering of its elements.
|
static void |
sort(List l,
Comparator c)
Sort a list according to a specified Comparator.
|
static void |
swap(List l,
int i,
int j)
Swaps the elements at the specified positions within the list.
|
static Collection |
synchronizedCollection(Collection c)
Returns a synchronized (thread-safe) collection wrapper backed by the
given collection.
|
static List |
synchronizedList(List l)
Returns a synchronized (thread-safe) list wrapper backed by the
given list.
|
static Map |
synchronizedMap(Map m)
Returns a synchronized (thread-safe) map wrapper backed by the given
map.
|
static Set |
synchronizedSet(Set s)
Returns a synchronized (thread-safe) set wrapper backed by the given
set.
|
static SortedMap |
synchronizedSortedMap(SortedMap m)
Returns a synchronized (thread-safe) sorted map wrapper backed by the
given map.
|
static SortedSet |
synchronizedSortedSet(SortedSet s)
Returns a synchronized (thread-safe) sorted set wrapper backed by the
given set.
|
static Collection |
unmodifiableCollection(Collection c)
Returns an unmodifiable view of the given collection.
|
static List |
unmodifiableList(List l)
Returns an unmodifiable view of the given list.
|
static Map |
unmodifiableMap(Map m)
Returns an unmodifiable view of the given map.
|
static Set |
unmodifiableSet(Set s)
Returns an unmodifiable view of the given set.
|
static SortedMap |
unmodifiableSortedMap(SortedMap m)
Returns an unmodifiable view of the given sorted map.
|
static SortedSet |
unmodifiableSortedSet(SortedSet s)
Returns an unmodifiable view of the given sorted set.
|
public static final Set EMPTY_SET
Serializable
public static final List EMPTY_LIST
Serializable
,
RandomAccess
public static final Map EMPTY_MAP
Serializable
public static int binarySearch(List l, Object key)
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.
l
- the list to search (must be sorted)key
- the value to search forClassCastException
- if key could not be compared with one of the
elements of lNullPointerException
- if a null element has compareTo calledsort(List)
public static int binarySearch(List l, Object key, Comparator c)
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.
l
- the list to search (must be sorted)key
- the value to search forc
- the comparator by which the list is sortedClassCastException
- if key could not be compared with one of the
elements of lNullPointerException
- if a null element is compared with natural
ordering (only possible when c is null)sort(List, Comparator)
public static void copy(List dest, List source)
dest
- the destination listsource
- the source listIndexOutOfBoundsException
- if the destination list is shorter
than the source list (the destination will be unmodified)UnsupportedOperationException
- if dest.listIterator() does not
support the set operationpublic static Enumeration enumeration(Collection c)
c
- the Collection to iterate overpublic static void fill(List l, Object val)
l
- the list to fill.val
- the object to vill the list with.UnsupportedOperationException
- if l.listIterator() does not
support the set operation.public static int indexOfSubList(List source, List target)
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.source
- the list to searchtarget
- the sublist to search forpublic static int lastIndexOfSubList(List source, List target)
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.source
- the list to searchtarget
- the sublist to search forpublic static ArrayList list(Enumeration e)
e
- the enumeration to put in a listArrayList
public static Object max(Collection c)
c
- the Collection to find the maximum element ofNoSuchElementException
- if c is emptyClassCastException
- if elements in c are not mutually comparableNullPointerException
- if null.compareTo is calledpublic static Object max(Collection c, Comparator order)
c
- the Collection to find the maximum element oforder
- the Comparator to order the elements by, or null for natural
orderingNoSuchElementException
- if c is emptyClassCastException
- if elements in c are not mutually comparableNullPointerException
- if null is compared by natural ordering
(only possible when order is null)public static Object min(Collection c)
c
- the Collection to find the minimum element ofNoSuchElementException
- if c is emptyClassCastException
- if elements in c are not mutually comparableNullPointerException
- if null.compareTo is calledpublic static Object min(Collection c, Comparator order)
c
- the Collection to find the minimum element oforder
- the Comparator to order the elements by, or null for natural
orderingNoSuchElementException
- if c is emptyClassCastException
- if elements in c are not mutually comparableNullPointerException
- if null is compared by natural ordering
(only possible when order is null)public static List nCopies(int n, Object o)
n
- the number of times to repeat the objecto
- the object to repeatIllegalArgumentException
- if n < 0List.addAll(Collection)
,
Serializable
,
RandomAccess
public static boolean replaceAll(List list, Object oldval, Object newval)
oldval == null ? e == null : oldval.equals(e)
.list
- the list to iterate overoldval
- the element to replacenewval
- the new value for the elementtrue
if a replacement occurred.UnsupportedOperationException
- if the list iterator does not allow
for the set operationClassCastException
- if newval is of a type which cannot be added
to the listIllegalArgumentException
- if some other aspect of newval stops
it being added to the listpublic static void reverse(List l)
l
- the list to reverseUnsupportedOperationException
- if l.listIterator() does not
support the set operationpublic static Comparator reverseOrder()
Comparable
,
Serializable
public static void rotate(List list, int distance)
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.
list
- the list to rotatedistance
- the distance to rotate by; unrestricted in valueUnsupportedOperationException
- if the list does not support setpublic static void shuffle(List l)
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.
l
- the list to shuffleUnsupportedOperationException
- if l.listIterator() does not
support the set operationpublic static void shuffle(List l, Random r)
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.
l
- the list to shuffler
- the source of randomness to use for the shuffleUnsupportedOperationException
- if l.listIterator() does not
support the set operationpublic static Set singleton(Object o)
o
- the single elementSerializable
public static List singletonList(Object o)
o
- the single elementSerializable
,
RandomAccess
public static Map singletonMap(Object key, Object value)
key
- the single keyvalue
- the single valueSerializable
public static void sort(List l)
l
- the List to sort (null
not permitted)ClassCastException
- if some items are not mutually comparableUnsupportedOperationException
- if the List is not modifiableNullPointerException
- if the list is null
, or contains
some element that is null
.Arrays.sort(Object[])
public static void sort(List l, Comparator c)
l
- the List to sort (null
not permitted)c
- the Comparator specifying the ordering for the elements, or
null
for natural orderingClassCastException
- if c will not compare some pair of itemsUnsupportedOperationException
- if the List is not modifiableNullPointerException
- if the List is null
or
null
is compared by natural ordering (only possible
when c is null
)Arrays.sort(Object[], Comparator)
public static void swap(List l, int i, int j)
l
- the list to work oni
- the first index to swapj
- the second indexUnsupportedOperationException
- if list.set is not supportedIndexOutOfBoundsException
- if either i or j is < 0 or >=
list.size()public static Collection synchronizedCollection(Collection c)
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.
c
- the collection to wrapSerializable
public static List synchronizedList(List l)
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.
l
- the list to wrapSerializable
,
RandomAccess
public static Map synchronizedMap(Map m)
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.
m
- the map to wrapSerializable
public static Set synchronizedSet(Set s)
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.
s
- the set to wrapSerializable
public static SortedMap synchronizedSortedMap(SortedMap m)
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.
m
- the sorted map to wrapSerializable
public static SortedSet synchronizedSortedSet(SortedSet s)
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.
s
- the sorted set to wrapSerializable
public static Collection unmodifiableCollection(Collection c)
UnsupportedOperationException
. Although this view
prevents changes to the structure of the collection and its elements, the values
referenced by the objects in the collection can still be modified.
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.
c
- the collection to wrapSerializable
public static List unmodifiableList(List l)
UnsupportedOperationException
.
Although this view prevents changes to the structure of the list and
its elements, the values referenced by the objects in the list can
still be modified.
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.
l
- the list to wrapSerializable
,
RandomAccess
public static Map unmodifiableMap(Map m)
UnsupportedOperationException
.
Although this view prevents changes to the structure of the map and its
entries, the values referenced by the objects in the map can still be
modified.
The returned Map implements Serializable, but can only be serialized if the map it wraps is likewise Serializable.
m
- the map to wrapSerializable
public static Set unmodifiableSet(Set s)
UnsupportedOperationException
.
Although this view prevents changes to the structure of the set and its
entries, the values referenced by the objects in the set can still be
modified.
The returned Set implements Serializable, but can only be serialized if the set it wraps is likewise Serializable.
s
- the set to wrapSerializable
public static SortedMap unmodifiableSortedMap(SortedMap m)
UnsupportedOperationException
.
Although this view prevents changes to the structure of the map and its
entries, the values referenced by the objects in the map can still be
modified.
The returned SortedMap implements Serializable, but can only be serialized if the map it wraps is likewise Serializable.
m
- the map to wrapSerializable
public static SortedSet unmodifiableSortedSet(SortedSet s)
UnsupportedOperationException
.
Although this view prevents changes to the structure of the set and its
entries, the values referenced by the objects in the set can still be
modified.
The returns SortedSet implements Serializable, but can only be serialized if the set it wraps is likewise Serializable.
s
- the set to wrapSerializable