Prev Class | Next Class | Frames | No Frames |
Summary: Nested | Field | Method | Constr | Detail: Nested | Field | Method | Constr |
java.lang.Object
java.util.Collections
public class Collections
extends Object
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
Field Summary | |
static List<E> |
|
static Map<K,V> |
|
static Set<E> |
|
Method Summary | |
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static |
|
static boolean |
|
static |
|
static |
|
static |
|
static int | |
static int |
|
static |
|
static |
|
static int |
|
static void |
|
static void |
|
static void |
|
static void | |
static void |
|
static |
|
static |
|
static |
|
Methods inherited from class java.lang.Object | |
clone , equals , extends Object> getClass , finalize , hashCode , notify , notifyAll , toString , wait , wait , wait |
public static final List<E> EMPTY_LIST
An immutable, serializable, empty List, which implements RandomAccess.
- See Also:
Serializable
,RandomAccess
public static final Map<K,V> EMPTY_MAP
An immutable, serializable, empty Map.
- See Also:
Serializable
public static final Set<E> EMPTY_SET
An immutable, serializable, empty Set.
- See Also:
Serializable
public staticArrayList list (Enumeratione)
Returns an ArrayList holding the elements visited by a given Enumeration. This method exists for interoperability between legacy APIs and the new Collection API.
- Parameters:
e
- the enumeration to put in a list
- Returns:
- a list containing the enumeration elements
- Since:
- 1.4
- See Also:
ArrayList
public staticCollection checkedCollection (Collectionc, Class type)
Returns a dynamically typesafe view of the given collection, where any modification is first checked to ensure that the type of the new data is appropriate. Although the addition of generics and parametrically-typed collections prevents an incorrect type of element being added to a collection at compile-time, via static type checking, this can be overridden by casting. In contrast, wrapping the collection within a dynamically-typesafe wrapper, using this and associated methods,guarantees that the collection will only contain elements of an appropriate type (provided it only contains such at the type of wrapping, and all subsequent access is via the wrapper). This can be useful for debugging the cause of aClassCastException
caused by erroneous casting, or for protecting collections from corruption by external libraries. 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:
c
- the collection to wrap in a dynamically typesafe wrappertype
- the type of elements the collection should hold.
- Returns:
- a dynamically typesafe view of the collection.
- Since:
- 1.5
- See Also:
Serializable
public staticCollection synchronizedCollection (Collectionc)
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:
c
- the collection to wrap
- Returns:
- a synchronized view of the collection
- See Also:
Serializable
public staticCollection unmodifiableCollection (T> 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 withUnsupportedOperationException
. 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.
- Parameters:
c
- the collection to wrap
- Returns:
- a read-only view of the collection
- See Also:
Serializable
public staticComparator 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:
- a comparator that imposes reverse natural ordering
- See Also:
Comparable
,Serializable
public staticComparator reverseOrder (Comparatorc)
Get a comparator that implements the reverse of the ordering specified by the given Comparator. If the Comparator is null, this is equivalent toreverseOrder()
. The return value of this method is Serializable, if the specified Comparator is either Serializable or null.
- Parameters:
c
- the comparator to invert
- Returns:
- a comparator that imposes reverse ordering
- Since:
- 1.5
- See Also:
Comparable
,Serializable
public staticEnumeration enumeration (Collectionc)
Returns an Enumeration over a collection. This allows interoperability with legacy APIs that require an Enumeration as input.
- Parameters:
c
- the Collection to iterate over
- Returns:
- an Enumeration backed by an Iterator over c
public staticList checkedList (Listl, Class type)
Returns a dynamically typesafe view of the given list, where any modification is first checked to ensure that the type of the new data is appropriate. Although the addition of generics and parametrically-typed collections prevents an incorrect type of element being added to a collection at compile-time, via static type checking, this can be overridden by casting. In contrast, wrapping the collection within a dynamically-typesafe wrapper, using this and associated methods,guarantees that the collection will only contain elements of an appropriate type (provided it only contains such at the type of wrapping, and all subsequent access is via the wrapper). This can be useful for debugging the cause of aClassCastException
caused by erroneous casting, or for protecting collections from corruption by external libraries. 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:
l
- the list to wraptype
- the type of the elements within the checked list.
- Returns:
- a dynamically typesafe view of the list
- See Also:
Serializable
,RandomAccess
public staticList nCopies (int n, T 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:
n
- the number of times to repeat the objecto
- the object to repeat
- Returns:
- a List consisting of n copies of o
- Throws:
IllegalArgumentException
- if n < 0
- See Also:
List.addAll(Collection)
,Serializable
,RandomAccess
public staticList singletonList (T o)
Obtain an immutable List consisting of a single element. The return value of this method is Serializable, and implements RandomAccess.
- Parameters:
o
- the single element
- Returns:
- an immutable List containing only o
- Since:
- 1.3
- See Also:
Serializable
,RandomAccess
public staticList synchronizedList (Listl)
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:
l
- the list to wrap
- Returns:
- a synchronized view of the list
- See Also:
Serializable
,RandomAccess
public staticList unmodifiableList (T> 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 withUnsupportedOperationException
. 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.
- Parameters:
l
- the list to wrap
- Returns:
- a read-only view of the list
- See Also:
Serializable
,RandomAccess
public staticQueue asLifoQueue (Dequedeque)
Returns a view of aDeque
as a stack or LIFO (Last-In-First-Out)Queue
. Each call to the LIFO queue corresponds to one equivalent method call to the underlying deque, with the exception ofCollection.addAll(Collection)
, which is emulated by a series ofDeque.push(E)
calls.
- Parameters:
deque
- the deque to convert to a LIFO queue.
- Returns:
- a LIFO queue.
- Since:
- 1.6
public staticSet checkedSet (Sets, Class type)
Returns a dynamically typesafe view of the given set, where any modification is first checked to ensure that the type of the new data is appropriate. Although the addition of generics and parametrically-typed collections prevents an incorrect type of element being added to a collection at compile-time, via static type checking, this can be overridden by casting. In contrast, wrapping the collection within a dynamically-typesafe wrapper, using this and associated methods,guarantees that the collection will only contain elements of an appropriate type (provided it only contains such at the type of wrapping, and all subsequent access is via the wrapper). This can be useful for debugging the cause of aClassCastException
caused by erroneous casting, or for protecting collections from corruption by external libraries. The returned Set implements Serializable, but can only be serialized if the set it wraps is likewise Serializable.
- Parameters:
s
- the set to wrap.type
- the type of the elements within the checked list.
- Returns:
- a dynamically typesafe view of the set
- See Also:
Serializable
public staticSet newSetFromMap (Mapmap)
Returns a set backed by the supplied map. The resulting set has the same performance, concurrency and ordering characteristics as the original map. The supplied map must be empty and should not be used after the set is created. Each call to the set corresponds to one equivalent method call to the underlying map, with the exception ofSet.addAll(Collection)
which is emulated by a series of calls toput
.
- Parameters:
map
- the map to convert to a set.
- Returns:
- a set backed by the supplied map.
- Throws:
IllegalArgumentException
- if the map is not empty.
- Since:
- 1.6
public staticSet singleton (T o)
Obtain an immutable Set consisting of a single element. The return value of this method is Serializable.
- Parameters:
o
- the single element
- Returns:
- an immutable Set containing only o
- See Also:
Serializable
public staticSet synchronizedSet (Sets)
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:
s
- the set to wrap
- Returns:
- a synchronized view of the set
- See Also:
Serializable
public staticSet unmodifiableSet (T> 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 withUnsupportedOperationException
. 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.
- Parameters:
s
- the set to wrap
- Returns:
- a read-only view of the set
- See Also:
Serializable
public staticSortedSet checkedSortedSet (SortedSets, Class type)
Returns a dynamically typesafe view of the given sorted set, where any modification is first checked to ensure that the type of the new data is appropriate. Although the addition of generics and parametrically-typed collections prevents an incorrect type of element being added to a collection at compile-time, via static type checking, this can be overridden by casting. In contrast, wrapping the collection within a dynamically-typesafe wrapper, using this and associated methods,guarantees that the collection will only contain elements of an appropriate type (provided it only contains such at the type of wrapping, and all subsequent access is via the wrapper). This can be useful for debugging the cause of aClassCastException
caused by erroneous casting, or for protecting collections from corruption by external libraries. The returned SortedSet implements Serializable, but can only be serialized if the set it wraps is likewise Serializable.
- Parameters:
s
- the set to wrap.type
- the type of the set's elements.
- Returns:
- a dynamically typesafe view of the set
- See Also:
Serializable
public staticSortedSet synchronizedSortedSet (SortedSets)
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:
s
- the sorted set to wrap
- Returns:
- a synchronized view of the sorted set
- See Also:
Serializable
public staticSortedSet unmodifiableSortedSet (SortedSets)
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 withUnsupportedOperationException
. 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.
- Parameters:
s
- the set to wrap
- Returns:
- a read-only view of the set
- See Also:
Serializable
public staticT max(T> c, T> 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:
c
- the Collection to find the maximum element oforder
- the Comparator to order the elements by, or null for natural ordering
- Returns:
- the maximum element of c
- Throws:
NoSuchElementException
- 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 staticT min(T> c, T> 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:
c
- the Collection to find the minimum element oforder
- the Comparator to order the elements by, or null for natural ordering
- Returns:
- the minimum element of c
- Throws:
NoSuchElementException
- 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 staticV> Map checkedMap(Map m, Class keyType, Class valueType)
Returns a dynamically typesafe view of the given map, where any modification is first checked to ensure that the type of the new data is appropriate. Although the addition of generics and parametrically-typed collections prevents an incorrect type of element being added to a collection at compile-time, via static type checking, this can be overridden by casting. In contrast, wrapping the collection within a dynamically-typesafe wrapper, using this and associated methods,guarantees that the collection will only contain elements of an appropriate type (provided it only contains such at the type of wrapping, and all subsequent access is via the wrapper). This can be useful for debugging the cause of aClassCastException
caused by erroneous casting, or for protecting collections from corruption by external libraries. The returned Map implements Serializable, but can only be serialized if the map it wraps is likewise Serializable.
- Parameters:
m
- the map to wrapkeyType
- the dynamic type of the map's keys.valueType
- the dynamic type of the map's values.
- Returns:
- a dynamically typesafe view of the map
- See Also:
Serializable
public staticV> Map singletonMap(K key, V value)
Obtain an immutable Map consisting of a single key-value pair. The return value of this method is Serializable.
- Parameters:
key
- the single keyvalue
- the single value
- Returns:
- an immutable Map containing only the single key-value pair
- Since:
- 1.3
- See Also:
Serializable
public staticV> Map synchronizedMap(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:
m
- the map to wrap
- Returns:
- a synchronized view of the map
- See Also:
Serializable
public staticV> Map unmodifiableMap(extends K, V> 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 withUnsupportedOperationException
. 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.
- Parameters:
m
- the map to wrap
- Returns:
- a read-only view of the map
- See Also:
Serializable
public staticV> SortedMap checkedSortedMap(SortedMap m, Class keyType, Class valueType)
Returns a dynamically typesafe view of the given sorted map, where any modification is first checked to ensure that the type of the new data is appropriate. Although the addition of generics and parametrically-typed collections prevents an incorrect type of element being added to a collection at compile-time, via static type checking, this can be overridden by casting. In contrast, wrapping the collection within a dynamically-typesafe wrapper, using this and associated methods,guarantees that the collection will only contain elements of an appropriate type (provided it only contains such at the type of wrapping, and all subsequent access is via the wrapper). This can be useful for debugging the cause of aClassCastException
caused by erroneous casting, or for protecting collections from corruption by external libraries. The returned SortedMap implements Serializable, but can only be serialized if the map it wraps is likewise Serializable.
- Parameters:
m
- the map to wrap.keyType
- the dynamic type of the map's keys.valueType
- the dynamic type of the map's values.
- Returns:
- a dynamically typesafe view of the map
- See Also:
Serializable
public staticV> SortedMap synchronizedSortedMap(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:
m
- the sorted map to wrap
- Returns:
- a synchronized view of the sorted map
- See Also:
Serializable
public staticV> SortedMap unmodifiableSortedMap(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 withUnsupportedOperationException
. 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.
- Parameters:
m
- the map to wrap
- Returns:
- a read-only view of the map
- See Also:
Serializable
public staticboolean addAll(T> c, T... a)
Adds all the specified elements to the given collection, in a similar way to theaddAll
method of theCollection
. However, this is a variable argument method which allows the new elements to be specified individually or in array form, as opposed to the list required by the collection'saddAll
method. This has benefits in both simplicity (multiple elements can be added without having to be wrapped inside a grouping structure) and efficiency (as a redundant list doesn't have to be created to add an individual set of elements or an array).
- Parameters:
c
- the collection to which the elements should be added.a
- the elements to be added to the collection.
- Returns:
- true if the collection changed its contents as a result.
- Throws:
UnsupportedOperationException
- if the collection does not support addition.NullPointerException
- if one or more elements in a are null, and the collection does not allow null elements. This exception is also thrown if eitherc
ora
are null.IllegalArgumentException
- if the collection won't allow an element to be added for some other reason.
- Since:
- 1.5
public staticboolean replaceAll(List list, T oldval, T newval)
Replace all instances of one object with another in the specified list. The list does not change size. An element e is replaced ifoldval == null ? e == null : oldval.equals(e)
.
- Parameters:
list
- the list to iterate overoldval
- the element to replacenewval
- the new value for the element
- Returns:
true
if a replacement occurred.
- Throws:
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 list
- Since:
- 1.4
public static boolean disjoint(Collection> c1, Collection> c2)
Returns true if the two specified collections have no elements in common. This method may give unusual results if one or both collections use a non-standard equality test. In the trivial case of comparing a collection with itself, this method returns true if, and only if, the collection is empty.
- Parameters:
c1
- the first collection to compare.c2
- the second collection to compare.
- Returns:
- true if the collections are disjoint.
- Throws:
NullPointerException
- if either collection is null.
- Since:
- 1.5
public staticextends Comparable super T>> void sort(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:
l
- the List to sort (null
not permitted)
- Throws:
ClassCastException
- if some items are not mutually comparableUnsupportedOperationException
- if the List is not modifiableNullPointerException
- if the list isnull
, or contains some element that isnull
.
- See Also:
Arrays.sort(Object[])
public staticextends Object & Comparable super T>> T max(T> 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:
c
- the Collection to find the maximum element of
- Returns:
- the maximum element of c
- Throws:
NoSuchElementException
- if c is emptyClassCastException
- if elements in c are not mutually comparableNullPointerException
- if null.compareTo is called
public staticextends Object & Comparable super T>> T min(T> 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:
c
- the Collection to find the minimum element of
- Returns:
- the minimum element of c
- Throws:
NoSuchElementException
- if c is emptyClassCastException
- if elements in c are not mutually comparableNullPointerException
- if null.compareTo is called
public static int frequency(Collection> c, Object o)
Returns the frequency of the specified object within the supplied collection. The frequency represents the number of occurrences of elements within the collection which returntrue
when compared with the object using theequals
method.
- Parameters:
c
- the collection to scan for occurrences of the object.o
- the object to locate occurrances of within the collection.
- Throws:
NullPointerException
- if the collection isnull
.
- Since:
- 1.5
public 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. Iftarget.size() > source.size()
, this returns -1, otherwise this implementation uses brute force, checking forsource.sublist(i, i + target.size()).equals(target)
for all possible i.
- Parameters:
source
- the list to searchtarget
- the sublist to search for
- Returns:
- the index where found, or -1
- Since:
- 1.4
public staticint binarySearch(T> l, T key, T> 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 forRandomAccess
lists, and uses a linear search with O(n) link traversals and log(n) comparisons withAbstractSequentialList
lists. Note: although the specification allows for an infinite loop if the list is unsorted, it will not happen in this (Classpath) implementation.
- Parameters:
l
- the list to search (must be sorted)key
- the value to search forc
- the comparator by which the list is sorted
- Returns:
- the index at which the key was found, or -n-1 if it was not found, where n is the index of the first value higher than key or a.length if there is no such value
- Throws:
ClassCastException
- 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)
- See Also:
sort(List, Comparator)
public staticint binarySearch(T>> l, T 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 forRandomAccess
lists, and uses a linear search with O(n) link traversals and log(n) comparisons withAbstractSequentialList
lists. Note: although the specification allows for an infinite loop if the list is unsorted, it will not happen in this (Classpath) implementation.
- Parameters:
l
- the list to search (must be sorted)key
- the value to search for
- Returns:
- the index at which the key was found, or -n-1 if it was not found, where n is the index of the first value higher than key or a.length if there is no such value
- Throws:
ClassCastException
- if key could not be compared with one of the elements of lNullPointerException
- if a null element has compareTo called
- See Also:
sort(List)
public 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. Iftarget.size() > source.size()
, this returns -1, otherwise this implementation uses brute force, checking forsource.sublist(i, i + target.size()).equals(target)
for all possible i.
- Parameters:
source
- the list to searchtarget
- the sublist to search for
- Returns:
- the index where found, or -1
- Since:
- 1.4
public static void reverse(List> l)
Reverse a given list. This method works in linear time.
- Parameters:
l
- the list to reverse
- Throws:
UnsupportedOperationException
- if l.listIterator() does not support the set operation
public static void rotate(List> list, int distance)
Rotate the elements in a list by a specified distance. After calling this method, the element now at indexi
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 eitherCollections.rotate(l, 4)
orCollections.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 elementa
forward two positions in the original example, useCollections.rotate(l.subList(1, 3+1), -1)
, which will result in[t, n, k, a, s]
. If the list is small or implementsRandomAccess
, 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
, callsreverse(List)
on the pieces, then reverses the overall list.
- Parameters:
list
- the list to rotatedistance
- the distance to rotate by; unrestricted in value
- Throws:
UnsupportedOperationException
- if the list does not support set
- Since:
- 1.4
public static void shuffle(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 implementRandomAccess
, a temporary array is used to acheive this speed, since it would be quadratic access otherwise.
- Parameters:
l
- the list to shuffle
- Throws:
UnsupportedOperationException
- if l.listIterator() does not support the set operation
public static void shuffle(List> l, 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 implementRandomAccess
, a temporary array is used to acheive this speed, since it would be quadratic access otherwise.
- Parameters:
l
- the list to shuffler
- the source of randomness to use for the shuffle
- Throws:
UnsupportedOperationException
- if l.listIterator() does not support the set operation
public static void swap(List> l, int i, int j)
Swaps the elements at the specified positions within the list. Equal positions have no effect.
- Parameters:
l
- the list to work oni
- the first index to swapj
- the second index
- Throws:
UnsupportedOperationException
- if list.set is not supportedIndexOutOfBoundsException
- if either i or j is < 0 or >= list.size()
- Since:
- 1.4
public staticvoid copy(T> dest, T> 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:
dest
- the destination listsource
- the source list
- Throws:
IndexOutOfBoundsException
- if the destination list is shorter than the source list (the destination will be unmodified)UnsupportedOperationException
- if dest.listIterator() does not support the set operation
public staticvoid fill(T> l, T val)
Replace every element of a list with a given value. This method runs in linear time.
- Parameters:
l
- the list to fill.val
- the object to vill the list with.
- Throws:
UnsupportedOperationException
- if l.listIterator() does not support the set operation.
public staticvoid sort(List l, T> 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:
l
- the List to sort (null
not permitted)c
- the Comparator specifying the ordering for the elements, ornull
for natural ordering
- Throws:
ClassCastException
- if c will not compare some pair of itemsUnsupportedOperationException
- if the List is not modifiableNullPointerException
- if the List isnull
ornull
is compared by natural ordering (only possible when c isnull
)
- See Also:
Arrays.sort(Object[], Comparator)