|
Generated by JDiff |
||||||||
| PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES | |||||||||
This file contains all the changes in documentation in the packagejava.utilas colored differences. Deletions are shownlike this, and additions are shown like this.
If no deletions or additions are shown in an entry, the HTML tags will be what has changed. The new HTML tags are shown in the differences. If no documentation existed, and then some was added in a later version, this change is noted in the appropriate class pages of differences, but the change is not shown on this page. Only changes in existing text are shown here. Similarly, documentation which was inherited from another class or interface is not shown here.
Note that an HTML error in the new documentation may cause the display of other documentation changes to be presented incorrectly. For instance, failure to close a <code> tag will cause all subsequent paragraphs to be displayed differently.
This class provides a skeletal implementation of the Collection interface to minimize the effort required to implement this interface.Class AbstractCollection, boolean addAll(Collection)To implement an unmodifiable collection the programmer needs only to extend this class and provide implementations for the iterator and size methods. (The iterator returned by the iterator method must implement hasNext and next.)
To implement a modifiable collection the programmer must additionally override this class's add method (which otherwise throws an UnsupportedOperationException) and the iterator returned by the iterator method must additionally implement its remove method.
The programmer should generally provide a void (no argument) and Collection constructor as per the recommendation in the Collection interface specification.
The documentation for each non-abstract methods in this class describes its implementation in detail. Each of these methods may be overridden if the collection being implemented admits a more efficient implementation. @author Josh Bloch @version 1.
16 0223 12/0203/0001 @see Collection @since 1.2
Adds all of the elements in the specified collection to this collection (optional operation). The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified collection is this collection and this collection is nonempty.)Class AbstractCollection, void clear()This implementation iterates over the specified collection and adds each object returned by the iterator to this collection in turn.
Note that this implementation will throw an UnsupportedOperationException unless add is overridden (assuming the specified collection is non-empty). @param c collection whose elements are to be added to this collection. @return true if this collection changed as a result of the call. @throws UnsupportedOperationException if this collection does not support the addAll method.
is@throwsnot supported by thisNullPointerException if the specified collection is null. @see #add(Object)
Removes all of the elements from this collection (optional operation). The collection will be empty after this call returns (unless it throws an exception).Class AbstractCollection, boolean containsAll(Collection)This implementation iterates over this collection removing each element using the Iterator.remove operation. Most implementations will probably choose to override this method for efficiency.
Note that this implementation will throw an UnsupportedOperationException if the iterator returned by this collection's iterator method does not implement the remove method and this collection is non-empty. @throws UnsupportedOperationException if the
removeclear method is not supported by this collection.
Returns true if this collection contains all of the elements in the specified collection.Class AbstractCollection, boolean remove(Object)This implementation iterates over the specified collection checking each element returned by the iterator in turn to see if it's contained in this collection. If all elements are so contained true is returned otherwise false. @param c collection to be checked for containment in this collection. @return true if this collection contains all of the elements in the specified collection. @throws NullPointerException if the specified collection is null. @see #contains(Object)
Removes a single instance of the specified element from this collection if it is present (optional operation). More formally removes an element e such that (o==null e==null : o.equals(e)) if the collection contains one or more such elements. Returns true if the collection contained the specified element (or equivalently if the collection changed as a result of the call).Class AbstractCollection, boolean removeAll(Collection)This implementation iterates over the collection looking for the specified element. If it finds the element it removes the element from the collection using the iterator's remove method.
Note that this implementation throws an UnsupportedOperationException if the iterator returned by this collection's iterator method does not implement the remove method and this collection contains the specified object. @param o element to be removed from this collection if present. @return true if the collection contained the specified element. @throws UnsupportedOperationException if the remove method is not supported by this collection.
Removes from this collection all of its elements that are contained in the specified collection (optional operation).Class AbstractCollection, boolean retainAll(Collection)This implementation iterates over this collection checking each element returned by the iterator in turn to see if it's contained in the specified collection. If it's so contained it's removed from this collection with the iterator's remove method.
Note that this implementation will throw an UnsupportedOperationException if the iterator returned by the iterator method does not implement the remove method and this collection contains one or more elements in common with the specified collection. @param c elements to be removed from this collection. @return true if this collection changed as a result of the call. @throws UnsupportedOperationException if the removeAll method is not supported by this collection. @throws NullPointerException if the specified collection is null. @see #remove(Object) @see #contains(Object)
Retains only the elements in this collection that are contained in the specified collection (optional operation). In other words removes from this collection all of its elements that are not contained in the specified collection.Class AbstractCollection, Object[] toArray(Object[])This implementation iterates over this collection checking each element returned by the iterator in turn to see if it's contained in the specified collection. If it's not so contained it's removed from this collection with the iterator's remove method.
Note that this implementation will throw an UnsupportedOperationException if the iterator returned by the iterator method does not implement the remove method and this collection contains one or more elements not present in the specified collection. @param c elements to be retained in this collection. @return true if this collection changed as a result of the call. @throws UnsupportedOperationException if the retainAll method is not supported by this Collection. @throws NullPointerException if the specified collection is null. @see #remove(Object) @see #contains(Object)
Returns an arraywith a runtime type iscontaining all of the elementsthatin this collection; the runtime type of thespecifiedreturned arrayandis thatcontains allof theelements in thisspecifiedcollectionarray. If the collection fits in the specified array it is returned therein. Otherwise a new array is allocated with the runtime type of the specified array and the size of this collection.If the collection fits in the specified array with room to spare (i.e. the array has more elements than the collection) the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the collection only if the caller knows that the collection does not contain any null elements.)
If this collection makes any guarantees as to what order its elements are returned by its iterator this method must return the elements in the same order.
This implementation checks if the array is large enough to contain the collection; if not it allocates a new array of the correct size and type (using reflection). Then it iterates over the collection storing each object reference in the next consecutive element of the array starting with element 0. If the array is larger than the collection a null is stored in the first location after the end of the collection. @param a the array into which the elements of the collection are to be stored if it is big enough; otherwise a new array of the same runtime type is allocated for this purpose. @return an array containing the elements of the collection. @throws NullPointerException if the specified array is null. @throws ArrayStoreException if the runtime type of the specified array is not a supertype of the runtime type of every element in this collection.
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array). For sequential access data (such as a linked list) AbstractSequentialList should be used in preference to this class.Class AbstractList, boolean addAll(int, Collection)To implement an unmodifiable list the programmer needs only to extend this class and provide implementations for the get(int index) and size() methods.
To implement a modifiable list the programmer must additionally override the set(int index Object element) method (which otherwise throws an UnsupportedOperationException. If the list is variable-size the programmer must additionally override the add(int index Object element) and remove(int index) methods.
The programmer should generally provide a void (no argument) and collection constructor as per the recommendation in the Collection interface specification.
Unlike the other abstract collection implementations the programmer does not have to provide an iterator implementation; the iterator and list iterator are implemented by this class on top the "random access" methods: get(int index) set(int index Object element) set(int index Object element) add(int index Object element) and remove(int index).
The documentation for each non-abstract methods in this class describes its implementation in detail. Each of these methods may be overridden if the collection being implemented admits a more efficient implementation. @author Josh Bloch @version 1.
31 0235 12/0203/0001 @see Collection @see List @see AbstractSequentialList @see AbstractCollection @since 1.2
Inserts all of the elements in the specified collection into this list at the specified position (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection's iterator. The behavior of this operation is unspecified if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list and it's nonempty.)Class AbstractList, List subList(int, int)This implementation gets an iterator over the specified collection and iterates over it inserting the elements obtained from the iterator into this list at the appropriate position one at a time using add(int Object). Many implementations will override this method for efficiency.
Note that this implementation throws an UnsupportedOperationException unless add(int Object) is overridden. @return true if this list changed as a result of the call. @param index index at which to insert the first element from the specified collection. @param c elements to be inserted into this List. @throws UnsupportedOperationException if the addAll method is not supported by this list. @throws ClassCastException if the class of an element of the specified collection prevents it from being added to this List. @throws IllegalArgumentException some aspect an element of the specified collection prevents it from being added to this List. @throws IndexOutOfBoundsException index out of range (index < 0 || index > size()). @throws NullPointerException if the specified collection is null.
Returns a view of the portion of this list between fromIndex inclusive and toIndex exclusive. (If fromIndex and toIndex are equal the returned list is empty.) The returned list is backed by this list so changes in the returned list are reflected in this list and vice-versa. The returned list supports all of the optional list operations supported by this list.This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by operating on a subList view instead of a whole list. For example the following idiom removes a range of elements from a list:
list.subList(from to).clear();Similar idioms may be constructed for indexOf and lastIndexOf and all of the algorithms in the Collections class can be applied to a subList.The semantics of the list returned by this method become undefined if the backing list (i.e. this list) is structurally modified in any way other than via the returned list. (Structural modifications are those that change the size of the list or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)
This implementation returns a list that subclasses AbstractList. The subclass stores in private fields the offset of the subList within the backing list the size of the subList (which can change over its lifetime) and the expected modCount value of the backing list. There are two variants of the subclass one of which implements RandomAccess. If this list implements RandomAccess the returned list will be an instance of the subclass that implements RandomAccess.
The subclass's set(int Object) get(int) add(int Object) remove(int) addAll(int Collection) and removeRange(int int) methods all delegate to the corresponding methods on the backing abstract list after bounds-checking the index and adjusting for the offset. The addAll(Collection c) method merely returns addAll(size c).
The listIterator(int) method returns a "wrapper object" over a list iterator on the backing list which is created with the corresponding method on the backing list. The iterator method merely returns listIterator() and the size method merely returns the subclass's size field.
All methods first check to see if the actual modCount of the backing list is equal to its expected value and throw a ConcurrentModificationException if it is not. @param fromIndex low endpoint (inclusive) of the subList. @param toIndex high endpoint (exclusive) of the subList. @return a view of the specified range within this list. @throws IndexOutOfBoundsException endpoint index value out of range (fromIndex < 0 || toIndex > size) @throws IllegalArgumentException endpoint indices out of order (fromIndex > toIndex)
This class provides a skeletal implementation of the Map interface to minimize the effort required to implement this interface.Class AbstractMap, void clear()To implement an unmodifiable map the programmer needs only to extend this class and provide an implementation for the entrySet method which returns a set-view of the map's mappings. Typically the returned set will in turn be implemented atop AbstractSet. This set should not support the add or remove methods and its iterator should not support the remove method.
To implement a modifiable map the programmer must additionally override this class's put method (which otherwise throws an UnsupportedOperationException) and the iterator returned by entrySet().iterator() must additionally implement its remove method.
The programmer should generally provide a void (no argument) and map constructor as per the recommendation in the Map interface specification.
The documentation for each non-abstract methods in this class describes its implementation in detail. Each of these methods may be overridden if the map being implemented admits a more efficient implementation. @author Josh Bloch @version 1.
21 0232 12/0203/0001 @see Map @see Collection @since 1.2
Removes all mappings from this map (optional operation).Class AbstractMap, Object clone()This implementation calls entrySet().clear(). Note that this implementation throws an UnsupportedOperationException if the entrySet does not support the clear operation. @throws UnsupportedOperationException clear is not supported by this map.
Class AbstractMap, boolean containsKey(Object)CreatesReturnsand returnsacopy of this object. The precise meaning ofshallow"copy" may depend on the class of the object. The general intent is that for any object x the expression: x.clone() = x will be true and that the expression: x.clone().getClass() == x.getClass() will be true but these are not absolute requirements. While it is typically the case that: x.clone().equals(x) will be true this is not an absolute requirement. Copyingan object will typically entail creating a new instance of its class but it also may require copying of internal data structures as well. No constructors are called. The method clone for class Object performs a specific cloning operation. First if the classof thisobject does not implement the interface Cloneable then aCloneNotSupportedExceptionAbstractMapis thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise this method creates a newinstanceof: theclass of this objectkeys andinitializes all its fields withvaluesexactly the contents of the corresponding fields of this object as if by assignment; the contents of the fieldsthemselves are notthemselvescloned.Thus this method performs@return a"shallow copy" of this object not a "deep copy" operation. The class Object does not itself implement the interface Cloneable so calling the clone method on an object whose class is Object will result in throwing an exception at run time. The clone method is implemented by the class Object as aconvenient general utility for subclasses that implement the interface Cloneable possibly also overriding the clone method in which case the overriding definition can refer to this utility definition by the call: super.clone() @return a cloneof thisinstance. @exception CloneNotSupportedException if the object's class does not support the Cloneable interface. Subclasses that override the clone method can also throw this exception to indicate that an instance cannot be cloned. @exception OutOfMemoryError if there is not enough memory. @see java.langmap.Cloneable
Returns true if this map contains a mapping for the specified key.Class AbstractMap, Object get(Object)This implementation iterates over entrySet() searching for an entry with the specified key. If such an entry is found true is returned. If the iteration terminates without finding such an entry false is returned. Note that this implementation requires linear time in the size of the map; many implementations will override this method. @param key key whose presence in this map is to be tested. @return true if this map contains a mapping for the specified key. @throws
ClassCastException if the specified key is of an inappropriate type for this map. @throwsNullPointerException key is null and this map does not not permit null keys.
Returns the value to which this map maps the specified key. Returns null if the map contains no mapping for this key. A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.Class AbstractMap, void putAll(Map)This implementation iterates over entrySet() searching for an entry with the specified key. If such an entry is found the entry's value is returned. If the iteration terminates without finding such an entry null is returned. Note that this implementation requires linear time in the size of the map; many implementations will override this method. @param key key whose associated value is to be returned. @return the value to which this map maps the specified key. @throws
ClassCastException if the specified key is of an inappropriate type for this map. @throwsNullPointerException if the key is null and this map does not not permit null keys. @see #containsKey(Object)
Copies all of the mappings from the specified map to this map (optional operation). These mappings will replace any mappings that this map had for any of the keys currently in the specified map.Class AbstractMap, Object remove(Object)This implementation iterates over the specified map's entrySet() collection and calls this map's put operation once for each entry returned by the iteration.
Note that this implementation throws an UnsupportedOperationException if this map does not support the put operation and the specified map is nonempty. @param t mappings to be stored in this map. @throws UnsupportedOperationException if the putAll operation is not supported by this map. @throws ClassCastException if the class of a key or value in the specified map prevents it from being stored in this map. @throws IllegalArgumentException if some aspect of a key or value in the specified map prevents it from being stored in this map. @throws NullPointerException the specified map is null or if this map does not permit null keys or values and the specified
key or valuemapiscontains null keys or values.
Removes the mapping for this key from this map if present (optional operation).This implementation iterates over entrySet() searching for an entry with the specified key. If such an entry is found its value is obtained with its getValue operation the entry is is removed from the Collection (and the backing map) with the iterator's remove operation and the saved value is returned. If the iteration terminates without finding such an entry null is returned. Note that this implementation requires linear time in the size of the map; many implementations will override this method.
Note that this implementation throws an UnsupportedOperationException if the entrySet iterator does not support the remove method and this map contains a mapping for the specified key. @param key key whose mapping is to be removed from the map. @return previous value associated with specified key or null if there was no entry for key. (A null return can also indicate that the map previously associated null with the specified key if the implementation supports null values.) @throws UnsupportedOperationException if the remove operation is not supported by this map.
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "sequential access" data store (such as a linked list). For random access data (such as an array) AbstractList should be used in preference to this class.Class AbstractSequentialList, boolean addAll(int, Collection)This class is the opposite of the AbstractList class in the sense that it implements the "random access" methods (get(int index) set(int index Object element) set(int index Object element) add(int index Object element) and remove(int index)) on top of the list's list iterator instead of the other way around.
To implement a list the programmer needs only to extend this class and provide implementations for the listIterator and size methods. For an unmodifiable list the programmer need only implement the list iterator's hasNext next hasPrevious previous and index methods.
For a modifiable list the programmer should additionally implement the list iterator's set method. For a variable-size list the programmer should additionally implement the list iterator's remove and add methods.
The programmer should generally provide a void (no argument) and collection constructor as per the recommendation in the Collection interface specification. @author Josh Bloch @version 1.
21 0225 12/0203/0001 @see Collection @see List @see AbstractList @see AbstractCollection @since 1.2
Inserts all of the elements in in the specified collection into this list at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection's iterator. The behavior of this operation is unspecified if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list and it's nonempty.) Optional operation.Class AbstractSequentialList, Object get(int)This implementation gets an iterator over the specified collection and a list iterator over this list pointing to the indexed element (with listIterator(index)). Then it iterates over the specified collection inserting the elements obtained from the iterator into this list one at a time using ListIterator.add followed by ListIterator.next (to skip over the added element).
Note that this implementation will throw an UnsupportedOperationException if the list iterator returned by the listIterator method does not implement the add operation. @return true if this list changed as a result of the call. @param index index at which to insert first element from the specified collection. @param c elements to be inserted into this list. @throws UnsupportedOperationException if the addAll operation is not supported by this list. @throws NullPointerException this list does not permit null elements and one of the elements of the specified collection is null. @throws ClassCastException if the class of the specified element prevents it from being added to this list. @throws IllegalArgumentException if some aspect of the specified element prevents it from being added to this list. @throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()). @throws NullPointerException if the specified collection is null.
Returns the element at the specified position in this list.Class AbstractSequentialList, ListIterator listIterator(int)This implementation first gets a list iterator pointing to the indexed element (with listIterator(index)). Then it gets the element using ListIterator.next and returns it. @param index index of element to return. @return the element at the specified position in this list.
* @param index index of element to return. *@throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).
Returns a list iterator over the elements in this list (in proper sequence). @param index index of first element to be returned from the list iterator (by a call to the next method) @return a list iterator over the elements in this list (in proper sequence).
This class provides a skeletal implementation of the Set interface to minimize the effort required to implement this interface.Class AbstractSet, boolean removeAll(Collection)The process of implementing a set by extending this class is identical to that of implementing a Collection by extending AbstractCollection except that all of the methods and constructors in subclasses of this class must obey the additional constraints imposed by the Set interface (for instance the add method must not permit addition of multiple intances of an object to a set).
Note that this class does not override any of the implementations from the AbstractCollection class. It merely adds implementations for equals and hashCode. @author Josh Bloch @version 1.
14 0217 12/0203/0001 @see Collection @see AbstractCollection @see Set @since 1.2
Removes from this set all of its elements that are contained in the specified collection (optional operation).This implementation determines which is the smaller of this set and the specified collection by invoking the size method on each. If this set has fewer elements then the implementation iterates over this set checking each element returned by the iterator in turn to see if it is contained in the specified collection. If it is so contained it is removed from this set with the iterator's remove method. If the specified collection has fewer elements then the implementation iterates over the specified collection removing from this set each element returned by the iterator using this set's remove method.
Note that this implementation will throw an UnsupportedOperationException if the iterator returned by the iterator method does not implement the remove method. @param c elements to be removed from this set. @return true if this set changed as a result of the call. @throws UnsupportedOperationException removeAll is not supported by this set. @throws NullPointerException if the specified collection is null. @see #remove(Object) @see #contains(Object)
Resizable-array implementation of the List interface. Implements all optional list operations and permits all elements including null. In addition to implementing the List interface this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector except that it is unsynchronized.)Class ArrayList, constructor ArrayList()The size isEmpty get set iterator and listIterator operations run in constant time. The add operation runs in amortized constant time that is adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added an ArrayList its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently and at least one of the threads modifies the list structurally it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time to prevent accidental unsynchronized access to the list:
List list = Collections.synchronizedList(new ArrayList(...));The iterators returned by this class's iterator and listIterator methods are fail-fast: if list is structurally modified at any time after the iterator is created in any way except through the iterator's own remove or add methods the iterator will throw a ConcurrentModificationException. Thus in the face of concurrent modification the iterator fails quickly and cleanly rather than risking arbitrary non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. @author Josh Bloch @version 1.
25 0236 12/0203/0001 @see Collection @see List @see LinkedList @see Vector @see Collections#synchronizedList(List) @since 1.2
Constructs an empty list with an initial capacity of ten.Class ArrayList, constructor ArrayList(Collection)
Constructs a list containing the elements of the specified collection in the order they are returned by the collection's iterator. The ArrayList instance has an initial capacity of 110% the size of the specified collection. @param c the collection whose elements are to be placed into this list. @throws NullPointerException if the specified collection is null.Class ArrayList, boolean addAll(Collection)
Appends all of the elements in the specified Collection to the end of this list in the order that they are returned by the specified Collection's Iterator. The behavior of this operation is undefined if the specified Collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified Collection is this list and this list is nonempty.) @param c the elements to be inserted into this list. @return true if this list changed as a result of the call. @throws IndexOutOfBoundsException if index out of range (index < 0 || index > size()). @throws NullPointerException if the specified collection is null.Class ArrayList, boolean addAll(int, Collection)
Inserts all of the elements in the specified Collection into this list starting at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified Collection's iterator. @param index index at which to insert first element from the specified collection. @param c elements to be inserted into this list. @return true if this list changed as a result of the call. @throws IndexOutOfBoundsException if index out of range (index < 0 || index > size()). @throws NullPointerException if the specified Collection is null.Class ArrayList, boolean contains(Object)
Returns true if this list contains the specified element. @param elem element whose presence in this List is to be tested. @returnClass ArrayList, Object[] toArray(Object[])trueif the specified element is present;falseotherwise.
Returns an array containing all of the elements in this list in the correct order. The; the runtime type of the returned array is that of the specified array. If the list fits in the specified array it is returned therein. Otherwise a new array is allocated with the runtime type of the specified array and the size of this list.If the list fits in the specified array with room to spare (i.e. the array has more elements than the list) the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements. @param a the array into which the elements of the list are to be stored if it is big enough; otherwise a new array of the same runtime type is allocated for this purpose. @return an array containing the elements of the list. @throws ArrayStoreException if the runtime type of a is not a supertype of the runtime type of every element in this list.
This class contains various methods for manipulating arrays (such as sorting and searching).Class Arrays, List asList(Object[])ItThis class also contains a static factory that allows arrays to be viewed as lists.The
documentationmethodsforin this class all throw a NullPointerException if thesorting andspecified arraysearchingreference is null.The documentation for the
methods contained in this class includes briefs description of the implementations. Such descriptions should be regarded as implementation notes rather than parts of the specification. Implementors should feel free to substitute other algorithms so long as the specification itself is adhered to. (For example the algorithm used by sort(Object[]) does not have to be a mergesort but it does have to be stable.) @author Josh Bloch @version 1.37 0244 12/0203/0001 @see Comparable @see Comparator @since 1.2
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs in combination with Collection.toArray. The returned list is serializableClass Arrays, int binarySearch(Object[], Object).and implements RandomAccess @param a the array by which the list will be backed. @return a list view of the specified array. @see Collection#toArray()
Searches the specified array for the specified object using the binary search algorithm. The array must be sorted into ascending order according to the natural ordering of its elements (as by Sort(Object[]) above) prior to making this call. If it is not sorted the results are undefined. (If the array contains elements that are not mutually comparable (for example strings and integers) it cannot be sorted according to the natural order of its elements hence results are undefined.) If the array contains multiple elements equal to the specified object there is no guarantee which one will be found. @param a the array to be searched. @param key the value to be searched for. @return index of the search key if it is contained in the list; otherwise (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. @throws ClassCastException if theClass Arrays, int binarySearch(double[], double)array contains elements that are not mutually comparable (for example strings and integers) or thesearch key in notmutuallycomparablewithto the elements of the array. @see Comparable @see #sort(Object[])
Searches the specified array of doubles for the specified value using the binary search algorithm. The array must be sorted (as by the sort method above) prior to making this call. If it is not sorted the results are undefined. If the array contains multiple elements with the specified value there is no guarantee which one will be found. This method considers all NaN values to be equivalent and equal. @param a the array to be searched. @param key the value to be searched for. @return index of the search key if it is contained in the list; otherwise (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. @see #sort(double[])Class Arrays, int binarySearch(float[], float)
Searches the specified array of floats for the specified value using the binary search algorithm. The array must be sorted (as by the sort method above) prior to making this call. If it is not sorted the results are undefined. If the array contains multiple elements with the specified value there is no guarantee which one will be found. This method considers all NaN values to be equivalent and equal. @param a the array to be searched. @param key the value to be searched for. @return index of the search key if it is contained in the list; otherwise (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. @see #sort(float[])Class Arrays, boolean equals(boolean[], boolean[])
Returns true if the two specified arrays ofClass Arrays, void sort(double[])equalsbooleans are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements and all corresponding pairs of elements in the two arrays are equal. In other words two arrays are equal if they contain the same elements in the same order. Also two array references are considered equal if both are null.@param a one array to be tested for equality. @param a2 the other array to be tested for equality. @return true if the two arrays are equal.
Sorts the specified array of doubles into ascending numerical order.Class Arrays, void sort(double[], int, int)The
<relation does not provide a total order on all floating-point values; although they are distinct numbers-0.0 == 0.0istrueand a NaN value compares neither less than greater than nor equal to any floating-point value even itself. To allow the sort to proceed instead of using the<relation to determine ascending numerical order this method uses the total order imposed by Double#compareTo This ordering differs from the<relation in that-0.0is treated as less than0.0and NaN is considered greater than any other floating-point value. For the purposes of sorting all NaN values are considered equivalent and equal.The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted.
Sorts the specified range of the specified array of doubles into ascending numerical order. The range to be sorted extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be sorted is empty.)Class Arrays, void sort(float[])The
<relation does not provide a total order on all floating-point values; although they are distinct numbers-0.0 == 0.0istrueand a NaN value compares neither less than greater than nor equal to any floating-point value even itself. To allow the sort to proceed instead of using the<relation to determine ascending numerical order this method uses the total order imposed by Double#compareTo This ordering differs from the<relation in that-0.0is treated as less than0.0and NaN is considered greater than any other floating-point value. For the purposes of sorting all NaN values are considered equivalent and equal.The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Sorts the specified array of floats into ascending numerical order.Class Arrays, void sort(float[], int, int)The
<relation does not provide a total order on all floating-point values; although they are distinct numbers-0.0f == 0.0fistrueand a NaN value compares neither less than greater than nor equal to any floating-point value even itself. To allow the sort to proceed instead of using the<relation to determine ascending numerical order this method uses the total order imposed by Float#compareTo This ordering differs from the<relation in that-0.0fis treated as less than0.0fand NaN is considered greater than any other floating-point value. For the purposes of sorting all NaN values are considered equivalent and equal.The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted.
Sorts the specified range of the specified array of floats into ascending numerical order. The range to be sorted extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be sorted is empty.)The
<relation does not provide a total order on all floating-point values; although they are distinct numbers-0.0f == 0.0fistrueand a NaN value compares neither less than greater than nor equal to any floating-point value even itself. To allow the sort to proceed instead of using the<relation to determine ascending numerical order this method uses the total order imposed by Float#compareTo This ordering differs from the<relation in that-0.0fis treated as less than0.0fand NaN is considered greater than any other floating-point value. For the purposes of sorting all NaN values are considered equivalent and equal.The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
This class implements a vector of bits that grows as needed. Each component of the bit set has aClass BitSet, void andNot(BitSet)booleanvalue. The bits of aBitSetare indexed by nonnegative integers. Individual indexed bits can be examined set or cleared. OneBitSetmay be used to modify the contents of anotherBitSetthrough logical AND logical inclusive OR and logical exclusive OR operations.By default all bits in the set initially have the value
false.Every bit set has a current size which is the number of bits of space currently in use by the bit set. Note that the size is related to the implementation of a bit set so it may change with implementation. The length of a bit set relates to logical length of a bit set and is defined independently of implementation.
Unless otherwise noted passing a null parameter to any of the methods in a
BitSetwill result in aNullPointerException. ABitSetis not safe for multithreaded use without external synchronization. @author Arthur van Hoff @author Michael McCloskey @version 1.46 0254 12/0203/0001 @since JDK1.0
Clears all of the bits in thisClass BitSet, int hashCode()BitSetwhose corresponding bit is set in the specifiedBitSet. @param set theBitSetwith which to mask thisBitSet. @since1JDK1.2
Returns a hash code value for this bit set. The has code depends only on which bits have been set within thisClass BitSet, void set(int)BitSet. The algorithm used to compute it may be described as follows.Suppose the bits in the
BitSetwere to be stored in an array oflongintegers called saybitsin such a manner that bitkis set in theBitSet(for nonnegative values ofk) if and only if the expression((k>>6) < bits.length) && ((bits[k>>6] & (1L << (bit & 0x3F))) = 0)is true. Then the following definition of thehashCodemethod would be a correct implementation of the actual algorithm:publicNote that the hash code values change if the set of bits is altered.synchronizedint hashCode() { long h = 1234; for (int i = bits.length; --i >= 0; ) { h ^= bits[i] * (i + 1); } return (int)((h >> 32) ^ h); }Overrides the
hashCodemethod ofObject. @return a hash code value for this bit set.
Sets the bitClass BitSet, String toString()specified byat the specified index totrue. @param bitIndex a bit index. @exception IndexOutOfBoundsException if the specified index is negative. @since JDK1.0
Returns a string representation of this bit set. For every index for which thisBitSetcontains a bit in the set state the decimal representation of that index is included in the result. Suchindeces aerindices are listed in order from lowest to highest separated by "$ " (a comma and a space) and surrounded by braces resulting in the usual mathematical notation for a set of integers.Overrides the
toStringmethod ofObject.Example:
BitSet drPepper = new BitSet();NowdrPepper.toString()returns "{}".
drPepper.set(2);NowdrPepper.toString()returns "{2}".
drPepper.set(4); drPepper.set(10);NowdrPepper.toString()returns "{2 4 10}". @return a string representation of this bit set.
Class Calendar, int get(int)Calendaris an abstract base class for converting between aDateobject and a set of integer fields such asYEARMONTHDAYHOURand so on. (ADateobject represents a specific instant in time with millisecond precision. See Date for information about theDateclass.)Subclasses of
Calendarinterpret aDateaccording to the rules of a specific calendar system. The platform provides one concrete subclass ofCalendar:GregorianCalendar. Future subclasses could represent the various types of lunar calendars in use in many parts of the world.Like other locale-sensitive classes
Calendarprovides a class methodgetInstancefor getting a generally useful object of this type.Calendar'sgetInstancemethod returns aobject whose time fields have been initialized with the current date and time:GregorianCalendarCalendarCalendar rightNow = Calendar.getInstance();A
Calendarobject can produce all the time field values needed to implement the date-time formatting for a particular language and calendar style (for example Japanese-Gregorian Japanese-Traditional).Calendardefines the range of values returned by certain fields as well as their meaning. For example the first month of the year has valueMONTH==JANUARYfor all calendars. Other values are defined by the concrete subclass such asERAandYEAR. See individual field documentation and subclass documentation for details.When a
Calendaris lenient it accepts a wider range of field values than it produces. For example a lenientGregorianCalendarinterpretsMONTH==JANUARYDAY_OF_MONTH== 32 as February 1. A non-lenientGregorianCalendarthrows an exception when given out-of-range field settings. When calendars recompute field values for return byget()they normalize them. For example aGregorianCalendaralways producesDAY_OF_MONTHvalues between 1 and the length of the month.
Calendardefines a locale-specific seven day week using two parameters: the first day of the week and the minimal days in first week (from 1 to 7). These numbers are taken from the locale resource data when aCalendaris constructed. They may also be specified explicitly through the API.When setting or getting the
WEEK_OF_MONTHorWEEK_OF_YEARfieldsCalendarmust determine the first week of the month or year as a reference point. The first week of a month or year is defined as the earliest seven day period beginning ongetFirstDayOfWeek()and containing at leastgetMinimalDaysInFirstWeek()days of that month or year. Weeks numbered ... -1 0 precede the first week; weeks numbered 2 3 ... follow it. Note that the normalized numbering returned byget()may be different. For example a specificCalendarsubclass may designate the week before week 1 of a year as week n of the previous year.When computing a
Datefrom time fields two special circumstances may arise: there may be insufficient information to compute theDate(such as only year and month but no day in the month) or there may be inconsistent information (such as "Tuesday July 15 1996" -- July 15 1996 is actually a Monday).Insufficient information. The calendar will use default information to specify the missing fields. This may vary by calendar; for the Gregorian calendar the default for a field is the same as that of the start of the epoch: i.e. YEAR = 1970 MONTH = JANUARY DATE = 1 etc.
Inconsistent information. If fields conflict the calendar will give preference to fields set more recently. For example when determining the day the calendar will look for one of the following combinations of fields. The most recent combination as determined by the most recently set single field will be used.
For the time of day:MONTH + DAY_OF_MONTH MONTH + WEEK_OF_MONTH + DAY_OF_WEEK MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK DAY_OF_YEAR DAY_OF_WEEK + WEEK_OF_YEARHOUR_OF_DAY AM_PM + HOURNote: for some non-Gregorian calendars different fields may be necessary for complete disambiguation. For example a full specification of the
historialhistorical Arabic astronomical calendar requires year month day-of-month and day-of-week in some cases.Note: There are certain possible ambiguities in interpretation of certain singular times which are resolved in the following ways:
2423:59 is the last minute of the day and 00:00"belongs"istothe first minute of thefollowingnext day.That isThus 23:59 on Dec 3119691999 <2400:00 on Jan 119702000 <2400:01:00on Jan 119702000.- Although historically not precise midnight also belongs to "am" and noon belongs to "pm" so on the same day 12:00 am (midnight) < 12:01 am and 12:00 pm (noon) < 12:01 pm
The date or time format strings are not part of the definition of a calendar as those must be modifiable or overridable by the user at runtime. Use DateFormat to format dates.
Field manipulation methods
Calendarfields can be changed using three methods:set()add()androll().
set(f value)changes fieldftovalue. In addition it sets an internal member variable to indicate that fieldfhas been changed. Although fieldfis changed immediately the calendar's milliseconds is not recomputed until the next call toget()getTime()orgetTimeInMillis()is made. Thus multiple calls toset()do not trigger multiple unnecessary computations. As a result of changing a field usingset()other fields may also change depending on the field the field value and the calendar system. In additionget(f)will not necessarily returnvalueafter the fields have been recomputed. The specifics are determined by the concrete calendar class.Example: Consider a
GregorianCalendaroriginally set to August 31 1999. Callingset(Calendar.MONTH Calendar.SEPTEMBER)sets the calendar to September 31 1999. This is a temporary internal representation that resolves to October 1 1999 ifgetTime()is then called. However a call toset(Calendar.DAY_OF_MONTH 30)before the call togetTime()sets the calendar to September 30 1999 since no recomputation occurs afterset()itself.
add(f delta)addsdeltato fieldf. This is equivalent to callingset(f get(f) + delta)with two adjustments:Add rule 1. The value of field
fafter the call minus the value of fieldfbefore the call isdeltamodulo any overflow that has occurred in fieldf. Overflow occurs when a field value exceeds its range and as a result the next larger field is incremented or decremented and the field value is adjusted back into its range.Add rule 2. If a smaller field is expected to be invariant but it is impossible for it to be equal to its prior value because of changes in its minimum or maximum after field
fis changed then its value is adjusted to be as close as possible to its expected value. A smaller field represents a smaller unit of time.HOURis a smaller field thanDAY_OF_MONTH. No adjustment is made to smaller fields that are not expected to be invariant. The calendar system determines what fields are expected to be invariant.In addition unlike
set()add()forces an immediate recomputation of the calendar's milliseconds and all fields.Example: Consider a
GregorianCalendaroriginally set to August 31 1999. Callingadd(Calendar.MONTH 13)sets the calendar to September 30 2000. Add rule 1 sets theMONTHfield to September since adding 13 months to August gives September of the next year. SinceDAY_OF_MONTHcannot be 31 in September in aGregorianCalendaradd rule 2 sets theDAY_OF_MONTHto 30 the closest possible value. Although it is a smaller fieldDAY_OF_WEEKis not adjusted by rule 2 since it is expected to change when the month changes in aGregorianCalendar.
roll(f delta)addsdeltato fieldfwithout changing larger fields. This is equivalent to callingadd(f delta)with the following adjustment:Roll rule. Larger fields are unchanged after the call. A larger field represents a larger unit of time.
DAY_OF_MONTHis a larger field thanHOUR.Example:
Consider a GregorianCalendar originally set to August 31 1999. Calling roll(Calendar.MONTH 8) sets the calendar to April 30 1999. Add rule 1 sets the MONTH field to April. Using a GregorianCalendar the DAY_OF_MONTH cannot be 31 in the month April. Add rule 2 sets it to the closest possible value 30. Finally the roll rule maintains the YEAR field value of 1999. Example: Consider a GregorianCalendar originally set to Sunday June 6 1999. Calling roll(Calendar.WEEK_OF_MONTH -1) sets the calendar to Tuesday June 1 1999 whereas calling add(Calendar.WEEK_OF_MONTH -1) sets the calendar to Sunday May 30 1999. This is because the roll rule imposes an additional constraint: The MONTH must not change when the WEEK_OF_MONTH is rolled. Taken together with add rule 1 the resultant date must be between Tuesday June 1 and Saturday June 5. According to add rule 2 the DAY_OF_WEEK an invariant when changing the WEEK_OF_MONTH is set to Tuesday the closest possible value to Sunday (where Sunday is the first day of theSeeweekint).Usage model. To motivate the behavior of
@see Date @see GregorianCalendar @see TimeZone @see java.text.DateFormat @version 1.add()androll()consider a user interface component with increment and decrement buttons for the month day and year and an underlyingGregorianCalendar. If the interface reads January 31 1999 and the user presses the month increment button what should it read If the underlying implementation usesset()it might read March 3 1999. A better result would be February 28 1999. Furthermore if the user presses the month increment button again it should read March 31 1999 not March 28 1999. By saving the original date and using eitheradd()orroll()depending on whether larger fields should be affected the user interface can behave as most users will intuitively expect.49 0169 12/1903/0001 @author Mark Davis David Goldsmith Chen-Lieh Huang Alan Liu @since JDK1.1
Gets the value for a given time field. @param field the given time field. @return the value for the given time field. @throws ArrayIndexOutOfBoundsException if specified field is out of range (field < 0 || field >= FIELD_COUNT).Class Calendar, Calendar getInstance()
Gets a calendar using the default time zone and locale. The Calendar returned is based on the current time in the default time zone with the default locale. @return a Calendar.
Class Calendar, Calendar getInstance(Locale)Gets a calendar using the default time zone and specified locale. The Calendar returned is based on the current time in the default time zone with the given locale. @param aLocale the locale for the week data @return a Calendar.
Class Calendar, Calendar getInstance(TimeZone)Gets a calendar using the specified time zone and default locale. The Calendar returned is based on the current time in the given time zone with the default locale. @param zone the time zone to use @return a Calendar.
Class Calendar, Calendar getInstance(TimeZone, Locale)Gets a calendar with the specified time zone and locale. The Calendar returned is based on the current time in the given time zone with the given locale. @param zone the time zone to use @param aLocale the locale for the week data @return a Calendar.
Class Calendar, Date getTime()Gets this Calendar's current time. @return the current time. @see #setTime @see #getTimeInMillisClass Calendar, long getTimeInMillis()
Gets this Calendar's current time as a long. @return the current time as UTC milliseconds from the epoch. @see #getTime @see #setTimeInMillisClass Calendar, void roll(int, boolean)
Time Field Rolling function.Class Calendar, void roll(int, int)RollsAdds or subtracts (up/down) a single unit of time on the given time field without changing larger fields. For example to roll the current date up by one day you can achieve it by calling:roll(Calendar.DATE true). When rolling on the year or Calendar.YEAR field it will roll the year value in the range between 1 and the value returned by calling getMaximum(Calendar.YEAR). When rolling on the month or Calendar.MONTH field other fields like date might conflict and need to be changed. For instance rolling the month on the date 01/31/96 will result in 02/29/96. When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field it will roll the hour value in the range between 0 and 23 which is zero-based. @param field the time field. @param up indicates if the value of the specified time field is to be rolled up or rolled down. Use true if rolling up false otherwise. @see Calendar#add @see Calendar#set
Time Field Rolling function.Class Calendar, void set(int, int)RollsAddup or down the specifiedtonumber of units on the given time fieldfield a signed amount without changing larger fields.(A negative roll amount means to roll down.)[NOTE: This default implementation on Calendar just repeatedly calls the version of roll() that takes a boolean and rolls by one unit. This may not always do the right thing. For example if the DAY_OF_MONTH field is 31 rolling through February will leave it set to 28. The GregorianCalendar version of this function takes care of this problem. Other subclasses should also provide overrides of this function that do the right thing. @param field the time field. @param amount the signed amount to add tofield. @since 1.2 @see Calendar#add @see Calendar#set
Sets the time field with the given value. @param field the given time field. @param value the value to be set for the given time field. @throws ArrayIndexOutOfBoundsException if specified field is out of range (field < 0 || field >= FIELD_COUNT).Class Calendar, void setTime(Date)
Sets this Calendar's current time with the given Date.Class Calendar, void setTimeInMillis(long)Note: Calling
setTime()withDate(Long.MAX_VALUE)orDate(Long.MIN_VALUE)may yield incorrect field values fromget(). @param date the given Date. @see #getTime @see #setTimeInMillis
Sets this Calendar's current time from the given long value. @paramClass Calendar, int DAY_OF_WEEK_IN_MONTHdatemillis the new time in UTC milliseconds from the epoch. @see #setTime @see #getTimeInMillis
Field number forClass Calendar, int DST_OFFSETgetandsetindicating the ordinal number of the day of the week within the current month. Together with theDAY_OF_WEEKfield this uniquely specifies a day within a month. UnlikeWEEK_OF_MONTHandWEEK_OF_YEARthis field's value does not depend ongetFirstDayOfWeek()orgetMinimalDaysInFirstWeek().DAY_OF_MONTH 1through7always correspond toDAY_OF_WEEK_IN_MONTH 1;8throughcorrespond to1514DAY_OF_WEEK_IN_MONTH 2and so on.DAY_OF_WEEK_IN_MONTH 0indicates the week beforeDAY_OF_WEEK_IN_MONTH 1. Negative values count back from the end of the month so the last Sunday of a month is specified asDAY_OF_WEEK = SUNDAY DAY_OF_WEEK_IN_MONTH = -1. Because negative values count backward they will usually be aligned differently within the month than positive values. For example if a month has 31 daysDAY_OF_WEEK_IN_MONTH -1will overlapDAY_OF_WEEK_IN_MONTH 5and the end of4. @see #DAY_OF_WEEK @see #WEEK_OF_MONTH
Field number forClass Calendar, int FIELD_COUNTgetandsetindicating the daylight savings offset in milliseconds.This field reflects the correct daylight saving offset value of the time zone of this
Calendarif theTimeZoneimplementation subclass supports historical Daylight Saving Time schedule changes.
The number ofClass Calendar, int MONTHdistictdistinct fields recognized bygetandset. Field numbers range from0..FIELD_COUNT-1.
Field number forClass Calendar, int ZONE_OFFSETgetandsetindicating the month. This is a calendar-specific value. The first month of the year isJANUARYwhich is 0; the last depends on the number of months in a year. @see #JANUARY @see #FEBRUARY @see #MARCH @see #APRIL @see #MAY @see #JUNE @see #JULY @see #AUGUST @see #SEPTEMBER @see #OCTOBER @see #NOVEMBER @see #DECEMBER @see #UNDECIMBER
Field number forgetandsetindicating the raw offset from GMT in milliseconds.This field reflects the correct GMT offset value of the time zone of this
Calendarif theTimeZoneimplementation subclass supports historical GMT offset changes.
The root interface in the collection hierarchy. A collection represents a group of objects known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The SDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.Class Collection, boolean add(Object)Bags or multisets (unordered collections that may contain duplicate elements) should implement this interface directly.
All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor which creates an empty collection and a constructor with a single argument of type Collection which creates a new collection with the same elements as its argument. In effect the latter constructor allows the user to copy any collection producing an equivalent collection of the desired implementation type. There is no way to enforce this convention (as interfaces cannot contain constructors) but all of the general-purpose Collection implementations in the
SDKJava platform libraries comply.The "destructive" methods contained in this interface that is the methods that modify the collection on which they operate are specified to throw UnsupportedOperationException if this collection does not support the operation. If this is the case these methods may but are not required to throw an UnsupportedOperationException if the invocation would have no effect on the collection. For example invoking the #addAll(Collection) method on an unmodifiable collection may but is not required to throw the exception if the collection to be added is empty.
Some collection implementations have restrictions on the elements that they may contain. For example some implementations prohibit null elements and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the collection may throw an exception or it may succeed at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface. @author Josh Bloch @version 1.
3132 02/0223/00 @see Set @see List @see Map @see SortedSet @see SortedMap @see HashSet @see TreeSet @see ArrayList @see LinkedList @see Vector @see Collections @see Arrays @see AbstractCollection @since 1.2
Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.)Class Collection, boolean addAll(Collection)Collections that support this operation may place limitations on what elements may be added to this collection. In particular some collections will refuse to add null elements and others will impose restrictions on the type of elements that may be added. Collection classes should clearly specify in their documentation any restrictions on what elements may be added.
If a collection refuses to add a particular element for any reason other than that it already contains the element it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns. @param o element whose presence in this collection is to be ensured. @return true if this collection changed as a result of the call @throws UnsupportedOperationException add is not supported by this collection. @throws ClassCastException class of the specified element prevents it from being added to this collection. @throws NullPointerException if the specified element is null and this collection does not support null elements. @throws IllegalArgumentException some aspect of this element prevents it from being added to this collection.
Adds all of the elements in the specified collection to this collection (optional operation). The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified collection is this collection and this collection is nonempty.) @param c elements to be inserted into this collection. @return true if this collection changed as a result of the call @throws UnsupportedOperationException if this collection does not support the addAll method. @throws ClassCastException if the class of an element of the specified collection prevents it from being added to this collection. @throws NullPointerException if the specified collection contains one or more null elements and this collection does not support null elements or if the specified collection is null. @throws IllegalArgumentException some aspect of an element of the specified collection prevents it from being added to this collection. @see #add(Object)Class Collection, boolean contains(Object)
Returns true if this collection contains the specified element. More formally returns true if and only if this collection contains at least one element e such that (o==null e==null : o.equals(e)). @param o element whose presence in this collection is to be tested. @return true if this collection contains the specified element @throws ClassCastException if the type of the specified element is incompatible with this collection (optional). @throws NullPointerException if the specified element is null and this collection does not support null elements (optional).Class Collection, boolean containsAll(Collection)
Returns true if this collection contains all of the elements in the specified collection. @param c collection to be checked for containment in this collection. @return true if this collection contains all of the elements in the specified collection @throws ClassCastException if the types of one or more elements in the specified collection are incompatible with this collection (optional). @throws NullPointerException if the specified collection contains one or more null elements and this collection does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #contains(Object)Class Collection, boolean remove(Object)
Removes a single instance of the specified element from this collection if it is present (optional operation). More formally removes an element e such that (o==null e==null : o.equals(e)) if this collection contains one or more such elements. Returns true if this collection contained the specified element (or equivalently if this collection changed as a result of the call). @param o element to be removed from this collection if present. @return true if this collection changed as a result of the call @throws ClassCastException if the type of the specified element is incompatible with this collection (optional). @throws NullPointerException if the specified element is null and this collection does not support null elements (optional). @throws UnsupportedOperationException remove is not supported by this collection.Class Collection, boolean removeAll(Collection)
Removes all this collection's elements that are also contained in the specified collection (optional operation). After this call returns this collection will contain no elements in common with the specified collection. @param c elements to be removed from this collection. @return true if this collection changed as a result of the call @throws UnsupportedOperationException if the removeAll method is not supported by this collection. @throws ClassCastException if the types of one or more elements in this collection are incompatible with the specified collection (optional). @throws NullPointerException if this collection contains one or more null elements and the specified collection does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #remove(Object) @see #contains(Object)Class Collection, boolean retainAll(Collection)
Retains only the elements in this collection that are contained in the specified collection (optional operation). In other words removes from this collection all of its elements that are not contained in the specified collection. @param c elements to be retained in this collection. @return true if this collection changed as a result of the call @throws UnsupportedOperationException if the retainAll method is not supported by this Collection. @throws ClassCastException if the types of one or more elements in this collection are incompatible with the specified collection (optional). @throws NullPointerException if this collection contains one or more null elements and the specified collection does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #remove(Object) @see #contains(Object)Class Collection, Object[] toArray(Object[])
Returns an array containing all of the elements in this collection;whosethe runtime type of the returned array is that of the specified array. If the collection fits in the specified array it is returned therein. Otherwise a new array is allocated with the runtime type of the specified array and the size of this collection.If this collection fits in the specified array with room to spare (i.e. the array has more elements than this collection) the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of this collection only if the caller knows that this collection does not contain any null elements.)
If this collection makes any guarantees as to what order its elements are returned by its iterator this method must return the elements in the same order.
Like the toArray method this method acts as bridge between array-based and collection-based APIs. Further this method allows precise control over the runtime type of the output array and may under certain circumstances be used to save allocation costs
Suppose l is a List known to contain only strings. The following code can be used to dump the list into a newly allocated array of String:
String[] x = (String[]) v.toArray(new String[0]);Note that toArray(new Object[0]) is identical in function to toArray(). @param a the array into which the elements of this collection are to be stored if it is big enough; otherwise a new array of the same runtime type is allocated for this purpose. @return an array containing the elements of this collection @throws ArrayStoreException the runtime type of the specified array is not a supertype of the runtime type of every element in this collection. @throws NullPointerException if the specified array is null.
This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections "wrappers" which return a new collection backed by a specified collection and a few other odds and ends.Class Collections, int binarySearch(List, Object)The methods of this class all throw a NullPointerException if the collections provided to them are null. The documentation for the polymorphic algorithms contained in this class generally includes a brief description of the implementation. Such descriptions should be regarded as implementation notes rather than parts of the specification. Implementors should feel free to substitute other algorithms so long as the specification itself is adhered to. (For example the algorithm used by sort does not have to be a mergesort but it does have to be stable.)
The "destructive" algorithms contained in this class that is the algorithms that modify the collection on which they operate are specified to throw UnsupportedOperationException if the collection does not support the appropriate mutation primitive(s) such as the set method. These algorithms may but are not required to throw this exception if an invocation would have no effect on the collection. For example invoking the sort method on an unmodifiable list that is already sorted may or may not throw UnsupportedOperationException. @author Josh Bloch @version 1.
46 0459 12/0603/0001 @see Collection @see Set @see List @see Map @since 1.2
Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method above) prior to making this call. If it is not sorted the results are undefined. If the list contains multiple elements equal to the specified object there is no guarantee which one will be found.Class Collections, int binarySearch(List, Object, Comparator)This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access).
It may run in n log(n) time if it is called on aIf"sequentialtheaccess"specified list(which provides linear-time positionaldoesaccess).notIfimplement thespecified list implementsRandomAccesstheandAbstracSequentialListisinterfacelarge this method will doa sequential search instead ofanaiterator-based binary search; this offers linear performanceinstead ofthatn logperforms O(n)performance if this methodlinkis calledtraversals andonO(logan)LinkedListelementobjectcomparisons. @param list the list to be searched. @param key the key to be searched for. @return index of the search key if it is contained in the list; otherwise (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. @throws ClassCastException if the list contains elements that are not mutually comparable (for example strings and integers) or the search key in not mutually comparable with the elements of the list. @see Comparable @see #sort(List)
Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the specified comparator (as by the Sort(List Comparator) method above) prior to making this call. If it is not sorted the results are undefined. If the list contains multiple elements equal to the specified object there is no guarantee which one will be found.Class Collections, Enumeration enumeration(Collection)This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access).
It may run in n log(n) time if it is called on aIf"sequentialtheaccess"specified list(which provides linear-time positionaldoesaccess).notIfimplement thespecified listRandomAccessimplements theand isAbstracSequentialListlargeinterfacethis this method will doa sequential search instead ofanaiterator-based binary search; this offers linear performanceinstead ofthatn logperforms O(n)performance if this methodlinkis calledtraversals andonO(logan)LinkedListelementobjectcomparisons. @param list the list to be searched. @param key the key to be searched for. @param c the comparator by which the list is ordered. A null value indicates that the elements' natural ordering should be used. @return index of the search key if it is contained in the list; otherwise (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. @throws ClassCastException if the list contains elements that are not mutually comparable using the specified comparator or the search key in not mutually comparable with the elements of the list using this comparator. @see Comparable @see #sort(List Comparator)
Returns an enumeration over the specified collection. This provides interoperatbility with legacy APIs that require an enumeration as input. @param c the collection for which an enumeration is to be returned. @return an enumeration over the specified collection. @see EnumerationClass Collections, void fill(List, Object)
Replaces all of the elements of the specified list with the specified element.Class Collections, void reverse(List)This method runs in linear time. @param list the list to be filled with the specified element. @param
oobj The element with which to fill the specified list. @throws UnsupportedOperationException if the specified list'sor its list-iterator does not support the set operation.
Reverses the order of the elements in the specified list.Class Collections, void shuffle(List)This method runs in linear time. @param
llist the list whose elements are to be reversed. @throws UnsupportedOperationException if the specified list'sor its list-iterator does not support the setoperationmethod.
Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.Class Collections, void shuffle(List, Random)The hedge "approximately" is used in the foregoing description because default source of randomenss is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits then the algorithm would choose permutations with perfect uniformity.
This implementation traverses the list backwards from the last element up to the second repeatedly swapping a randomly selected element into the "current position". Elements are randomly selected from the portion of the list that runs from the first element to the current position inclusive.
This method runs in linear time.
for aIf the"randomspecifiedaccess"list does not implement the RandomAccess interface and is large this implementation dumps the specified list(whichintoprovidesannear-constant-timearraypositionalbeforeaccess)shuffling it and dumps the shuffled array back into the list.It may requireThis avoids the quadratictimebehavior that would resultforfrom shuffling a "sequential access" list in place. @param list the list to be shuffled. @throws UnsupportedOperationException if the specified list'sor its list-iterator does not support the setoperationmethod.
Randomly permute the specified list using the specified source of randomness. All permutations occur with equal likelihood assuming that the source of randomness is fair.This implementation traverses the list backwards from the last element up to the second repeatedly swapping a randomly selected element into the "current position". Elements are randomly selected from the portion of the list that runs from the first element to the current position inclusive.
This method runs in linear time.
for aIf the"randomspecifiedaccess"list does not implement the RandomAccess interface and is large this implementation dumps the specified list(whichintoprovidesannear-constant-timearraypositional