Generated by
JDiff

java.util Documentation Differences

This file contains all the changes in documentation in the package java.util as colored differences. Deletions are shown like 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.

Class AbstractCollection

This class provides a skeletal implementation of the Collection interface to minimize the effort required to implement this interface.

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

Class AbstractCollection, boolean addAll(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.)

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@throws not supported by thisNullPointerException if the specified collection is null. @see #add(Object)

Class AbstractCollection, void clear()

Removes all of the elements from this collection (optional operation). The collection will be empty after this call returns (unless it throws an exception).

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.

Class AbstractCollection, boolean containsAll(Collection)

Returns true if this collection contains all of the elements in the specified collection.

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)

Class AbstractCollection, 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 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).

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.

Class AbstractCollection, boolean removeAll(Collection)

Removes from this collection all of its elements that are contained in the specified collection (optional operation).

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)

Class AbstractCollection, 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.

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)

Class AbstractCollection, Object[] toArray(Object[])

Returns an array with a runtime type iscontaining all of the elements thatin this collection; the runtime type of the specifiedreturned array andis that contains all of the elements in thisspecified collectionarray. 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.


Class AbstractList

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.

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

Class AbstractList, boolean addAll(int, Collection)

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.)

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.

Class AbstractList, List subList(int, int)

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)


Class AbstractMap

This class provides a skeletal implementation of the Map interface to minimize the effort required to implement this interface.

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

Class AbstractMap, void clear()

Removes all mappings from this map (optional operation).

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, Object clone()

CreatesReturns and returns a copy 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. Copying an 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 class of this object does not implement the interface Cloneable then a CloneNotSupportedExceptionAbstractMap is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise this method creates a new instance of: the class of this objectkeys and initializes all its fields withvalues exactly the contents of the corresponding fields of this object as if by assignment; the contents of the fieldsthemselves are not themselves cloned. 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 a convenient 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 clone of this instance. @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
Class AbstractMap, boolean containsKey(Object)

Returns true if this map contains a mapping for the specified key.

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. @throws NullPointerException key is null and this map does not not permit null keys.

Class AbstractMap, Object get(Object)

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.

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. @throws NullPointerException if the key is null and this map does not not permit null keys. @see #containsKey(Object)

Class AbstractMap, void putAll(Map)

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.

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 valuemap iscontains null keys or values.

Class AbstractMap, Object remove(Object)

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.


Class AbstractSequentialList

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.

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

Class AbstractSequentialList, boolean addAll(int, Collection)

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.

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.

Class AbstractSequentialList, Object get(int)

Returns the element at the specified position in this list.

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()).

Class AbstractSequentialList, ListIterator listIterator(int)

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).

Class AbstractSet

This class provides a skeletal implementation of the Set interface to minimize the effort required to implement this interface.

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

Class AbstractSet, boolean removeAll(Collection)

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)


Class ArrayList

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.)

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

Class ArrayList, constructor ArrayList()

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. @return true if the specified element is present; false otherwise.
Class ArrayList, Object[] toArray(Object[])

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.


Class Arrays

This class contains various methods for manipulating arrays (such as sorting and searching). ItThis class also contains a static factory that allows arrays to be viewed as lists.

The documentationmethods forin this class all throw a NullPointerException if the sorting andspecified array searchingreference 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

Class Arrays, List asList(Object[])

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 serializable. 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()
Class Arrays, int binarySearch(Object[], Object)

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 the array contains elements that are not mutually comparable (for example strings and integers) or the search key in not mutually comparable withto the elements of the array. @see Comparable @see #sort(Object[])
Class Arrays, int binarySearch(double[], double)

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 of 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.

Class Arrays, void sort(double[])

Sorts the specified array of doubles into ascending numerical order.

The < relation does not provide a total order on all floating-point values; although they are distinct numbers -0.0 == 0.0 is true and 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.0 is treated as less than 0.0 and 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.

Class Arrays, void sort(double[], int, int)

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.)

The < relation does not provide a total order on all floating-point values; although they are distinct numbers -0.0 == 0.0 is true and 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.0 is treated as less than 0.0 and 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

Class Arrays, void sort(float[])

Sorts the specified array of floats into ascending numerical order.

The < relation does not provide a total order on all floating-point values; although they are distinct numbers -0.0f == 0.0f is true and 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.0f is treated as less than 0.0f and 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.

Class Arrays, void sort(float[], int, int)

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.0f is true and 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.0f is treated as less than 0.0f and 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


Class BitSet

This class implements a vector of bits that grows as needed. Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined set or cleared. One BitSet may be used to modify the contents of another BitSet through 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 BitSet will result in a NullPointerException. A BitSet is 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

Class BitSet, void andNot(BitSet)

Clears all of the bits in this BitSet whose corresponding bit is set in the specified BitSet. @param set the BitSet with which to mask this BitSet. @since 1JDK1.2
Class BitSet, int hashCode()

Returns a hash code value for this bit set. The has code depends only on which bits have been set within this BitSet. The algorithm used to compute it may be described as follows.

Suppose the bits in the BitSet were to be stored in an array of long integers called say bits in such a manner that bit k is set in the BitSet (for nonnegative values of k) if and only if the expression

((k>>6) < bits.length) && ((bits[k>>6] & (1L << (bit & 0x3F))) = 0)
is true. Then the following definition of the hashCode method would be a correct implementation of the actual algorithm:
 public synchronized int hashCode() { long h = 1234; for (int i = bits.length; --i >= 0; ) { h ^= bits[i] * (i + 1); } return (int)((h >> 32) ^ h); }
Note that the hash code values change if the set of bits is altered.

Overrides the hashCode method of Object. @return a hash code value for this bit set.

Class BitSet, void set(int)

Sets the bit specified byat the specified index to true. @param bitIndex a bit index. @exception IndexOutOfBoundsException if the specified index is negative. @since JDK1.0
Class BitSet, String toString()

Returns a string representation of this bit set. For every index for which this BitSet contains a bit in the set state the decimal representation of that index is included in the result. Such indeces aerindices are listed in order from lowest to highest separated by " $&nbsp;" (a comma and a space) and surrounded by braces resulting in the usual mathematical notation for a set of integers.

Overrides the toString method of Object.

Example:

 BitSet drPepper = new BitSet();
Now drPepper.toString() returns "{}".

 drPepper.set(2);
Now drPepper.toString() returns "{2}".

 drPepper.set(4); drPepper.set(10);
Now drPepper.toString() returns "{2 4 10}". @return a string representation of this bit set.

Class Calendar

Calendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR MONTH DAY HOUR and so on. (A Date object represents a specific instant in time with millisecond precision. See Date for information about the Date class.)

Subclasses of Calendar interpret a Date according to the rules of a specific calendar system. The platform provides one concrete subclass of Calendar: GregorianCalendar. Future subclasses could represent the various types of lunar calendars in use in many parts of the world.

Like other locale-sensitive classes Calendar provides a class method getInstance for getting a generally useful object of this type. Calendar's getInstance method returns a GregorianCalendarCalendar object whose time fields have been initialized with the current date and time:

 Calendar rightNow = Calendar.getInstance(); 

A Calendar object 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). Calendar defines the range of values returned by certain fields as well as their meaning. For example the first month of the year has value MONTH == JANUARY for all calendars. Other values are defined by the concrete subclass such as ERA and YEAR. See individual field documentation and subclass documentation for details.

When a Calendar is lenient it accepts a wider range of field values than it produces. For example a lenient GregorianCalendar interprets MONTH == JANUARY DAY_OF_MONTH == 32 as February 1. A non-lenient GregorianCalendar throws an exception when given out-of-range field settings. When calendars recompute field values for return by get() they normalize them. For example a GregorianCalendar always produces DAY_OF_MONTH values between 1 and the length of the month.

Calendar defines 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 a Calendar is constructed. They may also be specified explicitly through the API.

When setting or getting the WEEK_OF_MONTH or WEEK_OF_YEAR fields Calendar must 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 on getFirstDayOfWeek() and containing at least getMinimalDaysInFirstWeek() 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 by get() may be different. For example a specific Calendar subclass may designate the week before week 1 of a year as week n of the previous year.

When computing a Date from time fields two special circumstances may arise: there may be insufficient information to compute the Date (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.

 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_YEAR 
For the time of day:
 HOUR_OF_DAY AM_PM + HOUR 

Note: 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:

  1. 2423:59 is the last minute of the day and 00:00 "belongs"is tothe first minute of the followingnext day. That isThus 23:59 on Dec 31 19691999 < 2400:00 on Jan 1 19702000 < 2400:01:00 on Jan 1 19702000.
  2. 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

Calendar fields can be changed using three methods: set() add() and roll().

set(f value) changes field f to value. In addition it sets an internal member variable to indicate that field f has been changed. Although field f is changed immediately the calendar's milliseconds is not recomputed until the next call to get() getTime() or getTimeInMillis() is made. Thus multiple calls to set() do not trigger multiple unnecessary computations. As a result of changing a field using set() other fields may also change depending on the field the field value and the calendar system. In addition get(f) will not necessarily return value after the fields have been recomputed. The specifics are determined by the concrete calendar class.

Example: Consider a GregorianCalendar originally set to August 31 1999. Calling set(Calendar.MONTH Calendar.SEPTEMBER) sets the calendar to September 31 1999. This is a temporary internal representation that resolves to October 1 1999 if getTime()is then called. However a call to set(Calendar.DAY_OF_MONTH 30) before the call to getTime() sets the calendar to September 30 1999 since no recomputation occurs after set() itself.

add(f delta) adds delta to field f. This is equivalent to calling set(f get(f) + delta) with two adjustments:

Add rule 1. The value of field f after the call minus the value of field f before the call is delta modulo any overflow that has occurred in field f. 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 f is 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. HOUR is a smaller field than DAY_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 GregorianCalendar originally set to August 31 1999. Calling add(Calendar.MONTH 13) sets the calendar to September 30 2000. Add rule 1 sets the MONTH field to September since adding 13 months to August gives September of the next year. Since DAY_OF_MONTH cannot be 31 in September in a GregorianCalendar add rule 2 sets the DAY_OF_MONTH to 30 the closest possible value. Although it is a smaller field DAY_OF_WEEK is not adjusted by rule 2 since it is expected to change when the month changes in a GregorianCalendar.

roll(f delta) adds delta to field f without changing larger fields. This is equivalent to calling add(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_MONTH is a larger field than HOUR.

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 theSee weekint).

Usage model. To motivate the behavior of add() and roll() consider a user interface component with increment and decrement buttons for the month day and year and an underlying GregorianCalendar. If the interface reads January 31 1999 and the user presses the month increment button what should it read If the underlying implementation uses set() 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 either add() or roll() depending on whether larger fields should be affected the user interface can behave as most users will intuitively expect.

@see Date @see GregorianCalendar @see TimeZone @see java.text.DateFormat @version 1.49 0169 12/1903/0001 @author Mark Davis David Goldsmith Chen-Lieh Huang Alan Liu @since JDK1.1
Class Calendar, int get(int)

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 #getTimeInMillis
Class 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 #setTimeInMillis
Class Calendar, void roll(int, boolean)

Time Field Rolling function. 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

Class Calendar, void roll(int, int)

Time Field Rolling function. RollsAdd up or down the specifiedto number 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 to field. @since 1.2 @see Calendar#add @see Calendar#set
Class Calendar, void set(int, int)

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.

Note: Calling setTime() with Date(Long.MAX_VALUE) or Date(Long.MIN_VALUE) may yield incorrect field values from get(). @param date the given Date. @see #getTime @see #setTimeInMillis

Class Calendar, void setTimeInMillis(long)

Sets this Calendar's current time from the given long value. @param datemillis the new time in UTC milliseconds from the epoch. @see #setTime @see #getTimeInMillis
Class Calendar, int DAY_OF_WEEK_IN_MONTH

Field number for get and set indicating the ordinal number of the day of the week within the current month. Together with the DAY_OF_WEEK field this uniquely specifies a day within a month. Unlike WEEK_OF_MONTH and WEEK_OF_YEAR this field's value does not depend on getFirstDayOfWeek() or getMinimalDaysInFirstWeek(). DAY_OF_MONTH 1 through 7 always correspond to DAY_OF_WEEK_IN_MONTH 1; 8 through 1514 correspond to DAY_OF_WEEK_IN_MONTH 2 and so on. DAY_OF_WEEK_IN_MONTH 0 indicates the week before DAY_OF_WEEK_IN_MONTH 1. Negative values count back from the end of the month so the last Sunday of a month is specified as DAY_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 days DAY_OF_WEEK_IN_MONTH -1 will overlap DAY_OF_WEEK_IN_MONTH 5 and the end of 4. @see #DAY_OF_WEEK @see #WEEK_OF_MONTH
Class Calendar, int DST_OFFSET

Field number for get and set indicating the daylight savings offset in milliseconds.

This field reflects the correct daylight saving offset value of the time zone of this Calendar if the TimeZone implementation subclass supports historical Daylight Saving Time schedule changes.

Class Calendar, int FIELD_COUNT

The number of distictdistinct fields recognized by get and set. Field numbers range from 0..FIELD_COUNT-1.
Class Calendar, int MONTH

Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year is JANUARY which 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
Class Calendar, int ZONE_OFFSET

Field number for get and set indicating the raw offset from GMT in milliseconds.

This field reflects the correct GMT offset value of the time zone of this Calendar if the TimeZone implementation subclass supports historical GMT offset changes.


Class Collection

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.

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

Class Collection, boolean add(Object)

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.)

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.

Class Collection, boolean addAll(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.


Class Collections

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.

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

Class Collections, int binarySearch(List, Object)

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.

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 "sequentialthe access"specified list (which provides linear-time positionaldoes access).not Ifimplement the specified list implementsRandomAccess theand AbstracSequentialListis interfacelarge this method will do a sequential search instead ofan aiterator-based binary search; this offers linear performance instead ofthat n logperforms O(n) performance if this methodlink is calledtraversals and onO(log an) LinkedListelement objectcomparisons. @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)

Class Collections, int binarySearch(List, Object, Comparator)

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.

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 "sequentialthe access"specified list (which provides linear-time positionaldoes access).not Ifimplement the specified listRandomAccess implements theand is AbstracSequentialListlarge interfacethis this method will do a sequential search instead ofan aiterator-based binary search; this offers linear performance instead ofthat n logperforms O(n) performance if this methodlink is calledtraversals and onO(log an) LinkedListelement objectcomparisons. @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)

Class Collections, Enumeration enumeration(Collection)

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 Enumeration
Class Collections, void fill(List, Object)

Replaces all of the elements of the specified list with the specified element.

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's or its list-iterator does not support the set operation.

Class Collections, void reverse(List)

Reverses the order of the elements in the specified list.

This method runs in linear time. @param llist the list whose elements are to be reversed. @throws UnsupportedOperationException if the specified list's or its list-iterator does not support the set operationmethod.

Class Collections, void shuffle(List)

Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.

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 "randomspecified access"list does not implement the RandomAccess interface and is large this implementation dumps the specified list (whichinto providesan near-constant-timearray positionalbefore access)shuffling it and dumps the shuffled array back into the list. It may requireThis avoids the quadratic timebehavior that would result forfrom shuffling a "sequential access" list in place. @param list the list to be shuffled. @throws UnsupportedOperationException if the specified list's or its list-iterator does not support the set operationmethod.

Class Collections, void shuffle(List, Random)

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 "randomspecified access"list does not implement the RandomAccess interface and is large this implementation dumps the specified list (whichinto providesan near-constant-timearray positionalbefore access)shuffling it and dumps the shuffled array back into the list. It may requireThis avoids the quadratic timebehavior that would result forfrom shuffling a "sequential access" list in place. @param list the list to be shuffled. @param rnd the source of randomness to use to shuffle the list. @throws UnsupportedOperationException if the specified list's or its list-iterator does not support the set operation.

Class Collections, List unmodifiableList(List)

Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list and attempts to modify the returned list whether direct or via its iterator result in an UnsupportedOperationException.

The returned list will be serializable if the specified list is serializable. Similarly the returned list will implement RandomAccess if the specified list does. the @param list the list for which an unmodifiable view is to be returned. @return an unmodifiable view of the specified list.


Class Comparator

A comparison function which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as TreeSet or TreeMap).

The ordering imposed by a Comparator c on a set of elements S is said to be consistent with equals if and only if (compare((Object)e1 (Object)e2)==0) has the same boolean value as e1.equals((Object)e2) for every e1 and e2 in S.

Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit Comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map) which is defined in terms of equals.

For example if one adds two keys a and b such that (a.equals((Object)b) && c.compare((Object)a (Object)b) = 0) to a sorted set with comparator c the second add operation will return false (and the size of the sorted set will not increase) because a and b are equivalent from the sorted set's perspective.

Note: It is generally a good idea for comparators to implement java.io.Serializable as they may be used as ordering methods in serializable data structures (like TreeSet TreeMap). In order for the data structure to serialize successfully the comparator (if provided) must implement Serializable.

For the mathematically inclined the relation that defines the total order that a given comparator c imposes on a given set of objects S is:

 {(x y) such that c.compare((Object)x (Object)y) <= 0}. 
The quotient for this total order is:
 {(x y) such that xc.compareTocompare((Object)x (Object)y) == 0}. 
It follows immediately from the contract for compare that the quotient is an equivalence relation on S and that the natural ordering is a total order on S. When we say that the ordering imposed by c on S is consistent with equals we mean that the quotient for the natural ordering is the equivalence relation defined by the objects' equals(Object) method(s):
 {(x y) such that x.equals((Object)y)}. 
@author Josh Bloch @version 1.15 0217 12/0203/0001 @see Comparable @see Arrays#sort(Object[] Comparator) @see TreeMap @see TreeSet @see SortedMap @see SortedSet @see java.io.Serializable @since 1.2

Class ConcurrentModificationException

This exception may be thrown by methods that have detected concurrent modification of a backingan object when such modification is not permissible.

For example it is not generally permssible for one thread to modify a Collection while another thread is iterating over it. In general the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the collection implementations provided by the SDKJRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators as they fail quickly and cleanly rather that risking arbitrary non-deterministic behavior at an undetermined time in the future.

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object the object may throw this exception. For example if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator the iterator will thow this exception.

Note that fail-fast behavior cannot be guaranteed as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast operations throw ConcurrentModificationException on a best-effort basis. Therefore it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs. @author Josh Bloch @version 1.11 0214 12/0203/0001 @see Collection @see Iterator @see ListIterator @see Vector @see LinkedList @see HashSet @see Hashtable @see TreeMap @see AbstractList @since 1.2


Class Date

The class Date represents a specific instant in time with millisecond precision.

Prior to JDK 1.1 the class Date had two additional functions. It allowed the interpretation of dates as year month day hour minute and second values. It also allowed the formatting and parsing of date strings. Unfortunately the API for these functions was not amenable to internationalization. As of JDK 1.1 the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.

Although the Date class is intended to reflect coordinated universal time (UTC) it may not do so exactly depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC however about once every year or two there is an extra second called a "leap second." The leap second is always added as the last second of the day and always on December 31 or June 30. For example the last minute of the year 1995 was 61 seconds long thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.

Some computer standards are defined in terms of Greenwich mean time (GMT) which is equivalent to universal time (UT). GMT is the "civil" name for the standard; UT is the "scientific" name for the same standard. The distinction between UTC and UT is that UTC is based on an atomic clock and UT is based on astronomical observations which for all practical purposes is an invisibly fine hair to split. Because the earth's rotation is not uniform (it slows down and speeds up in complicated ways) UT does not always flow uniformly. Leap seconds are introduced as needed into UTC so as to keep UTC within 0.9 seconds of UT1 which is a version of UT with certain corrections applied. There are other time and date systems as well; for example the time scale used by the satellite-based global positioning system (GPS) is synchronized to UTC but is not adjusted for leap seconds. An interesting source of further information is the U.S. Naval Observatory particularly the Directorate of Time at:

 http://tycho.usno.navy.mil 

and their definitions of "Systems of Time" at:

 http://tycho.usno.navy.mil/systime.html 

In all methods of class Date that accept or return year month date hours minutes and seconds values the following representations are used:

In all cases arguments given to methods for these purposes need not fall within the indicated ranges; for example a date may be specified as January 32 and is interpreted as meaning February 1. @author James Gosling @author Arthur van Hoff @author Alan Liu @version 1.69 0271 12/0903/01 @see java.text.DateFormat @see java.util.Calendar @see java.util.TimeZone @since JDK1.0

Class Date, long UTC(int, int, int, int, int, int)

Determines the date and time based on the arguments. The arguments are interpreted as a year month day of the month hour of the day minute within the hour and second within the minute exactly as for the Date constructor with six arguments except that the arguments are interpreted relative to UTC rather than to the local time zone. The time indecatedindicated is returned represented as the distance measured in milliseconds of that time from the epoch (00:00:00 GMT on January 1 1970). @param year the year minus 1900. @param month the month between 0-11. @param date the day of the month between 1-31. @param hrs the hours between 0-23. @param min the minutes between 0-59. @param sec the seconds between 0-59. @return the number of milliseconds since January 1 1970 00:00:00 GMT for the date and time specified by the arguments. @see java.util.Calendar @deprecated As of JDK version 1.1 replaced by Calendar.set(year + 1900 month date hrs min sec) or GregorianCalendar(year + 1900 month date hrs min sec) using a UTC TimeZone followed by Calendar.getTime().getTime().
Class Date, int getTimezoneOffset()

Returns the offset measured in minutes for the local time zone relative to UTC that is appropriate for the time represented by this Date object.

For example in Massachusetts five time zones west of Greenwich:

 new Date(96 1 14).getTimezoneOffset() returns 300
because on February 14 1996 standard time (Eastern Standard Time) is in use which is offset five hours from UTC; but:
 new Date(96 5 1).getTimezoneOffset() returns 240
because on May 1 1996 daylight savings time (Eastern Daylight Time) is in use which is offset only four hours from UTC.

This method produces tehthe same result as if it computed:

 (this.getTime() - UTC(this.getYear() this.getMonth() this.getDate() this.getHours() this.getMinutes() this.getSeconds())) / (60 * 1000) 
@return the time-zone offset in minutes for the current locale. @see java.util.Calendar @see java.util.TimeZone @deprecated As of JDK version 1.1 replaced by Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET).
Class Date, String toGMTString()

Creates a string representation of this Date object of the form: d mon yyyy hh:mm:ss GMT
where:

The result does not depend on the local time zone. @return a string representation of this date using the Internet GMT conventions. @see java.text.DateFormat @see java.util.Date#toString() @see java.util.Date#toLocaleString() @deprecated As of JDK version 1.1 replaced by DateFormat.format(Date date) using a GMT TimeZone. Class Date, String toString()

Converts this Date object to a String of the form:
 dow mon dd hh:mm:ss zzz yyyy
where: @return a string representation of this date. @see java.util.Date#toLocaleString() @see java.util.Date#toGMTString()

Class Dictionary

The Dictionary class is the abstract parent of any class such as Hashtable which maps keys to values. Every key and every value is an object. In any one Dictionary object every key is associated with at most one value. Given a Dictionary and a key the associated element can be looked up. Any non-null object can be used as a key and as a value.

As a rule the equals method should be used by implementations of this class to decide if two keys are the same.

NOTE: This class is obsolete. New implementations should implement the Map interface rather than extendidng this class. @author unascribed @version 1.15 0216 12/0203/0001 @see java.util.Map @see java.lang.Object#equals(java.lang.Object) @see java.lang.Object#hashCode() @see java.util.Hashtable @since JDK1.0


Class EmptyStackException

Thrown by methods in the Stack class to indicate that the stack is empty. @author Jonathan Payne @version 1.17 0218 12/0203/0001 @see java.util.Stack @since JDK1.0

Class Enumeration

An object that implements the Enumeration interface generates a series of elements one at a time. Successive calls to the nextElement method return successive elements of the series.

For example to print all elements of a vector v:

 for (Enumeration e = v.elements() ; e.hasMoreElements() ;) { System.out.println(e.nextElement());
}

Methods are provided to enumerate through the elements of a vector the keys of a hashtable and the values in a hashtable. Enumerations are also used to specify the input streams to a SequenceInputStream.

NOTE: The functionality of this interface is duplicated by the Iterator interface. In addition Iterator adds an optional remove operation and has shorter method names. New implementations should consider using Iterator in preference to Enumeration. @see java.util.Iterator @see java.io.SequenceInputStream @see java.util.Enumeration#nextElement() @see java.util.Hashtable @see java.util.Hashtable#elements() @see java.util.Hashtable#keys() @see java.util.Vector @see java.util.Vector#elements() @author Lee Boynton @version 1.18 0219 12/0203/0001 @since JDK1.0


Class GregorianCalendar

GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar used by most of the world.

The standard (Gregorian) calendar has 2 eras BC and AD.

This implementation handles a single discontinuity which corresponds by default to the date the Gregorian calendar was instituted (October 15 1582 in some countries later in others). The cutover date may be changed by the caller by calling setGregorianChange().

Historically in those countries which adopted the Gregorian calendar first October 4 1582 was thus followed by October 15 1582. This calendar models this correctly. Before the Gregorian cutover GregorianCalendar implements the Julian calendar. The only difference between the Gregorian and the Julian calendar is the leap year rule. The Julian calendar specifies leap years every four years whereas the Gregorian calendar omits century years which are not divisible by 400.

GregorianCalendar implements proleptic Gregorian and Julian calendars. That is dates are computed by extrapolating the current rules indefinitely far backward and forward in time. As a result GregorianCalendar may be used for all years to generate meaningful and consistent results. However dates obtained using GregorianCalendar are historically accurate only from March 1 4 AD onward when modern Julian calendar rules were adopted. Before this date leap year rules were applied irregularly and before 45 BC the Julian calendar did not even exist.

Prior to the institution of the Gregorian calendar New Year's Day was March 25. To avoid confusion this calendar always uses January 1. A manual adjustment may be made if desired for dates that are prior to the Gregorian changeover and which fall between January 1 and March 24.

Values calculated for the WEEK_OF_YEAR field range from 1 to 53. Week 1 for a year is the earliest seven day period starting on getFirstDayOfWeek() that contains at least getMinimalDaysInFirstWeek() days from that year. It thus depends on the values of getMinimalDaysInFirstWeek() getFirstDayOfWeek() and the day of the week of January 1. Weeks between week 1 of one year and week 1 of the following year are numbered sequentially from 2 to 52 or 53 (as needed).

For example January 1 1998 was a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (these are the values reflecting ISO 8601 and many national standards) then week 1 of 1998 starts on December 29 1997 and ends on January 4 1998. If however getFirstDayOfWeek() is SUNDAY then week 1 of 1998 starts on January 4 1998 and ends on January 10 1998; the first three days of 1998 then are part of week 53 of 1997.

Values calculated for the WEEK_OF_MONTH field range from 0 or 1 to 4 or 56. Week 1 of a month (the days with WEEK_OF_MONTH = 1) is the earliest set of at least getMinimalDaysInFirstWeek() contiguous days in that month ending on the day before getFirstDayOfWeek(). Unlike week 1 of a year week 1 of a month may be shorter than 7 days need not start on getFirstDayOfWeek() and will not include days of the previous month. Days of a month before week 1 have a WEEK_OF_MONTH of 0.

For example if getFirstDayOfWeek() is SUNDAY and getMinimalDaysInFirstWeek() is 4 then the first week of January 1998 is Sunday January 4 through Saturday January 10. These days have a WEEK_OF_MONTH of 1. Thursday January 1 through Saturday January 3 have a WEEK_OF_MONTH of 0. If getMinimalDaysInFirstWeek() is changed to 3 then January 1 through January 3 have a WEEK_OF_MONTH of 1.

Example:

 // get the supported ids for GMT-08:00 (Pacific Standard Time) String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000); // if no ids were returned something is wrong. get out. if (ids.length == 0) System.exit(0); // begin output System.out.println("Current Time"); // create a Pacific Standard Time time zone SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000 ids[0]); // set up rules for daylight savings time pdt.setStartRule(Calendar.APRIL 1 Calendar.SUNDAY 2 * 60 * 60 * 1000); pdt.setEndRule(Calendar.OCTOBER -1 Calendar.SUNDAY 2 * 60 * 60 * 1000); // create a GregorianCalendar with the Pacific Daylight time zone // and the current date and time Calendar calendar = new GregorianCalendar(pdt); Date trialTime = new Date(); calendar.setTime(trialTime); // print out a bunch of interesting things System.out.println("ERA: " + calendar.get(Calendar.ERA)); System.out.println("YEAR: " + calendar.get(Calendar.YEAR)); System.out.println("MONTH: " + calendar.get(Calendar.MONTH)); System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR)); System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH)); System.out.println("DATE: " + calendar.get(Calendar.DATE)); System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH)); System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR)); System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK)); System.out.println("DAY_OF_WEEK_IN_MONTH: " + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH)); System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM)); System.out.println("HOUR: " + calendar.get(Calendar.HOUR)); System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY)); System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE)); System.out.println("SECOND: " + calendar.get(Calendar.SECOND)); System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND)); System.out.println("ZONE_OFFSET: " + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); System.out.println("DST_OFFSET: " + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); System.out.println("Current Time with hour reset to 3"); calendar.clear(Calendar.HOUR_OF_DAY); // so doesn't override calendar.set(Calendar.HOUR 3); System.out.println("ERA: " + calendar.get(Calendar.ERA)); System.out.println("YEAR: " + calendar.get(Calendar.YEAR)); System.out.println("MONTH: " + calendar.get(Calendar.MONTH)); System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR)); System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH)); System.out.println("DATE: " + calendar.get(Calendar.DATE)); System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH)); System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR)); System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK)); System.out.println("DAY_OF_WEEK_IN_MONTH: " + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH)); System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM)); System.out.println("HOUR: " + calendar.get(Calendar.HOUR)); System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY)); System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE)); System.out.println("SECOND: " + calendar.get(Calendar.SECOND)); System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND)); System.out.println("ZONE_OFFSET: " + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); // in hours System.out.println("DST_OFFSET: " + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); // in hours 
@see Calendar @see TimeZone @version 1.5366 @author David Goldsmith Mark Davis Chen-Lieh Huang Alan Liu @since JDK1.1
Class GregorianCalendar, void add(int, int)

Overrides Calendar Date Arithmetic function. Adds the specified (signed) amount of time to the given time field based on the calendar's rules.

Add rule 1. The value of field after the call minus the value of field before the call is amount modulo any overflow that has occurred in field. 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 is 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. HOUR is a smaller field than DAY_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.

@param field the time field. @param amount the amount of date or time to be added to the field. @exception IllegalArgumentException if an unknown field is given.
Class GregorianCalendar, void roll(int, boolean)

OverridesAdds Calendar Time Field Rolling function.or Rollssubtracts (up/down) a single unit of time on the given time field without changing larger fields. @param

fieldExample: Consider a GregorianCalendar originally set to December 31 1999. Calling roll(Calendar.MONTH true) sets the timecalendar to January 31 1999. The Year field is unchanged because it is a larger field than MONTH.

@param up Indicatesindicates if rollingthe value of the specified time field is to be rolled up or rollingrolled down. the fieldUse true valueif rolling up false otherwise. @exception IllegalArgumentException if an unknown field value is given. @see GregorianCalendar#add @see GregorianCalendar#set
Class GregorianCalendar, void roll(int, int)

RollAdd to field a signed amount without changing larger fields. A negative roll amount means to subtract from field without changing larger fields.

Example: Consider a GregorianCalendar originally set to August 31 1999. Calling roll(Calendar.MONTH 8) sets the calendar to April 30 1999. Using a GregorianCalendar the DAY_OF_MONTH field cannot be 31 in the month April. DAY_OF_MONTH is set to the closest possible value 30. The YEAR field maintains the value of 1999 because it is a larger field bythan MONTH.

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 the week).

@param field the time field. @param amount the
signed amount to add to field. @since 1.2 @see GregorianCalendar#add @see GregorianCalendar#set

Class HashMap

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular it does not guarantee that the order will remain constant over time.

This implementation provides constant-time performance for the basic operations (get and put) assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus it's very important not to set the intialinitial capacity too high (or the load factor too low) if iteration performance is important.

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity the capacity is roughly doubled by calling the rehash method.

As a general rule the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor no rehash operations will ever occur.

If many mappings are to be stored in a HashMap instance creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table.

Note that this implementation is not synchronized. If multiple threads access this map concurrently and at least one of the threads modifies the map structurally it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time to prevent accidental unsynchronized access to the map:

 Map m = Collections.synchronizedMap(new HashMap(...)); 

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map 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 Doug Lea @author Josh Bloch @author Arthur van Hoff @version 1.38 0250 12/0203/0001 @see Object#hashCode() @see Collection @see Map @see TreeMap @see Hashtable @since 1.2

Class HashMap, constructor HashMap()

Constructs aan new empty mapHashMap with athe default initial capacity (16) and load factor which is the default load factor (0.75).
Class HashMap, constructor HashMap(Map)

Constructs a new mapHashMap with the same mappings as the givenspecified mapMap. The mapHashMap is created with a capacity of twice the number of mappings indefault the givenload factor map(0.75) or 11and an (whicheverinitial iscapacity greater)sufficient and a default load factor which isto hold the mappings in the specified 0.75Map. @param tm the map whose mappings are to be placed in this map. @throws NullPointerException if the specified map is null.
Class HashMap, constructor HashMap(int)

Constructs aan new empty mapHashMap with the specified initial capacity and the default load factor which is (0.75). @param initialCapacity the initial capacity of the HashMap. @throws IllegalArgumentException if the initial capacity is less than zeronegative.
Class HashMap, constructor HashMap(int, float)

Constructs aan new empty mapHashMap with the specified initial capacity and the specified load factor. @param initialCapacity theThe initial capacity of the HashMap. @param loadFactor theThe load factor of the HashMap. @throws IllegalArgumentException if the initial capacity is less than zeronegative or if the load factor is nonpositive.
Class HashMap, boolean containsKey(Object)

Returns true if this map contains a mapping for the specified key. @param key The key whose presence in this map is to be tested @return true if this map contains a mapping for the specified key. @param key key whose presence in this Map is to be tested.
Class HashMap, Object get(Object)

Returns the value to which this map maps the specified key. Returnsis mapped in this identity hash map or 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 is also possible that the map explicitly maps the key to null. The containsKey operationmethod may be used to distinguish these two cases. @param key the key whose associated value is to be returned. @return the value to which this map maps the specified key. @paramor keynull key whose associated value is to beif the map contains no mapping for returnedthis key. @see #put(Object Object)
Class HashMap, void putAll(Map)

Copies all of the mappings from the specified map to this one.map These mappings will replace any mappings that this map had for any of the keys currently in the specified Mapmap. @param t Mappingsmappings to be stored in this map. @throws NullPointerException if the specified map is null.

Class HashSet

This class implements the Set interface backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular it does not guarantee that the order will remain constant over time. This class permits the null element.

This class offers constant time performance for the basic operations (add remove contains and size) assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus it's very important not to set the intialinitial capacity too high (or the load factor too low) if iteration performance is important.

Note that this implementation is not synchronized. If multiple threads access a set concurrently and at least one of the threads modifies the set it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time to prevent accidental unsynchronized access to the HashSet instance:

 Set s = Collections.synchronizedSet(new HashSet(...)); 

The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created in any way except through the iterator's own remove method the Iterator throws 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.19 0225 12/0203/0001 @see Collection @see Set @see TreeSet @see Collections#synchronizedSet(Set) @see HashMap @since 1.2

Class HashSet, constructor HashSet()

Constructs a new empty set; the backing HashMap instance has default initial capacity (16) and load factor which is (0.75).
Class HashSet, constructor HashSet(Collection)

Constructs a new set containing the elements in the specified collection. The capacity of the backing HashMap instance is twice the size of thecreated with default load factor specified(0.75) collection or elevenand an initial (whichevercapacity issufficient greater)to andcontain the default load factor (whichelements isin 0.75)the is usedspecified collection. @param c the collection whose elements are to be placed into this set. @throws NullPointerException if the specified collection is null.
Class HashSet, boolean remove(Object)

Removes the givenspecified element from this set if it is present. @param o object to be removed from this set if present. @return true if the set contained the specified element.

Class Hashtable

This class implements a hashtable which maps keys to values. Any non-null object can be used as a key or as a value.

To successfully store and retrieve objects from a hashtable the objects used as keys must implement the hashCode method and the equals method.

An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case a "hash collision" a single bucket stores multiple entries which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity the capacity is increased by calling the rehash method.

Generally the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations including get and put).

The initial capacity controls a tradeoff between wasted space and the need for rehash operations which are time-consuming. No rehash operations will ever occur if the initial capacity is greater than the maximum number of entries the Hashtable will contain divided by its load factor. However setting the initial capacity too high can waste space.

If many entries are to be made into a Hashtable creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

This example creates a hashtable of numbers. It uses the names of the numbers as keys:

 Hashtable numbers = new Hashtable(); numbers.put("one" new Integer(1)); numbers.put("two" new Integer(2)); numbers.put("three" new Integer(3)); 

To retrieve a number use the following code:

 Integer n = (Integer)numbers.get("two"); if (n = null) { System.out.println("two = " + n); } 

As of the Java 2 platform v1.2 this class has been retrofitted to implement Map so that it becomes a part of Java's collection framework. Unlike the new collection implementations Hashtable is synchronized.

The Iterators returned by the iterator and listIterator methods of the Collections returned by all of Hashtable's "collection view methods" are fail-fast: if the Hashtable 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. The Enumerations returned by Hashtable's keys and values methods are not fail-fast.

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 Arthur van Hoff @author Josh Bloch @version 1.84 0990 12/2413/01 @see Object#equals(java.lang.Object) @see Object#hashCode() @see Hashtable#rehash() @see Collection @see Map @see HashMap @see TreeMap @since JDK1.0

Class Hashtable, constructor Hashtable()

Constructs a new empty hashtable with a default initial capacity (11) and load factor which is 0.75.
Class Hashtable, constructor Hashtable(Map)

Constructs a new hashtable with the same mappings as the given Map. The hashtable is created with a capacity of twice the number of entriesan initial capacity sufficient to hold the mappings in the given Map or 11 (whichever is greater) and a default load factor which is 0.75. @param t the map whose mappings are to be placed in this map. @throws NullPointerException if the specified map is null. @since 1.2
Class Hashtable, boolean equals(Object)

Compares the specified Object with this Map for equality as per the definition in the Map interface. @param o object to be compared for equality with this Hashtable @return true if the specified Object is equal to this Map. @see Map#equals(Object) @since 1.2
Class Hashtable, void putAll(Map)

Copies all of the mappings from the specified Map to this Hashtable These mappings will replace any mappings that this Hashtable had for any of the keys currently in the specified Map. @param t Mappings to be stored in this map. @throws NullPointerException if the specified map is null. @since 1.2

Class Iterator

An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways: @author Josh Bloch @version 1.14 0216 12/0203/0001 @see Collection @see ListIterator @see Enumeration @since 1.2
Class Iterator, Object next()

Returns the next element in the interationiteration. @return the next element in the iteration. @exception NoSuchElementException iteration has no more elements.

Class LinkedList

Linked list implementation of the List interface. Implements all optional list operations and permits all elements (including null). In addition to implementing the List interface the LinkedList class provides uniformly named methods to get remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack queue or double-ended queue (deque).

All of the stack/queue/deque operations could be easily recast in terms of the standard list operations. They're included here primarily for convenience though they may run slightly faster than the equivalent List operations.

All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the begining or the end whichever is closer to the specified index.

Note that this implementation is not synchronized. If multiple threads access a list 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; 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 LinkedList(...)); 

The iterators returned by the this class's iterator and listIterator methods are fail-fast: if the 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.32 0243 12/0203/0001 @see List @see ArrayList @see Vector @see Collections#synchronizedList(List) @since 1.2

Class LinkedList, constructor LinkedList(Collection)

Constructs a list containing the elements of the specified collection in the order they are returned by the collection's iterator. @param c the collection whose elements are to be placed into this list. @throws NullPointerException if the specified collection is null.
Class LinkedList, 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. @throwsreturn IndexOutOfBoundsExceptiontrue if the specified indexthis list changed isas a outresult of rangethe (indexcall. <@throws 0NullPointerException ||if indexthe >specified size())collection is null.
Class LinkedList, 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 the specified index is out of range (index < 0 || index > size()). @throws NullPointerException if the specified collection is null.
Class LinkedList, Object getFirst()

Returns the first element in this list. @return the first element in this list. @throws NoSuchElementException if this list is empty.
Class LinkedList, Object[] toArray(Object[])

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. @throws NullPointerException if the specified array is null.


Class List

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list) and search for elements in the list.

Unlike sets lists typically allow duplicate elements. More formally lists typically allow pairs of elements e1 and e2 such that e1.equals(e2) and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates by throwing runtime exceptions when the user attempts to insert them but we expect this usage to be rare.

The List interface places additional stipulations beyond those specified in the Collection interface on the contracts of the iterator add remove equals and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class for example). Thus iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator called a ListIterator that allows element insertion and replacement and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements extreme caution is advised: the equals and hashCode methods are no longer well defined on a such a list.

Some list 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 list 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.32 0236 12/0203/0001 @see Collection @see Set @see ArrayList @see LinkedList @see Vector @see Arrays#asList(Object[]) @see Collections#nCopies(int Object) @see Collections#EMPTY_LIST @see AbstractList @see AbstractSequentialList @since 1.2

Class List, boolean add(Object)

Appends the specified element to the end of this list (optional operation).

Lists that support this operation may place limitations on what elements may be added to this list. In particular some lists will refuse to add null elements and others will impose restrictions on the type of elements that may be added. List classes should clearly specify in their documentation any restrictions on what elements may be added. @param o element to be appended to this list. @return true (as per the general contract of the Collection.add method). @throws UnsupportedOperationException if the add method is not supported by this list. @throws ClassCastException if the class of the specified element prevents it from being added to this list. @throws NullPointerException if the specified element is null and this list does not support null elements. @throws IllegalArgumentException if some aspect of this element prevents it from being added to this collectionlist.

Class List, void add(int, Object)

Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). @param index index at which the specified element is to be inserted. @param element element to be inserted. @throws UnsupportedOperationException if the add method is not supported by this list. @throws ClassCastException if the class of the specified element prevents it from being added to this list. @throws NullPointerException if the specified element is null and this list does not support null elements. @throws IllegalArgumentException if some aspect of the specified element prevents it from being added to this list. @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > size()).
Class List, 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 (optional operation). 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.) @param c collection whose elements are to be added to this list. @return true if this list changed as a result of the call. @throws UnsupportedOperationException if the addAll method is not supported by this list. @throws ClassCastException if the class of an element in the specified collection prevents it from being added to this list. @throws NullPointerException if the specified collection contains one or more null elements and this list does not support null elements or if the specified collection is null. @throws IllegalArgumentException if some aspect of an element in the specified collection prevents it from being added to this list. @see #add(Object)
Class List, boolean addAll(int, Collection)

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 this 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.) @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 UnsupportedOperationException if the addAll method is not supported by this list. @throws ClassCastException if the class of one of elements of the specified collection prevents it from being added to this list. @throws NullPointerException if the specified collection contains one or more null elements and this list does not support null elements or if the specified collection is null. @throws IllegalArgumentException if some aspect of one of elements of the specified collection prevents it from being added to this list. @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > size()).
Class List, boolean contains(Object)

Returns true if this list contains the specified element. More formally returns true if and only if this list contains at least one element e such that (o==null   e==null : o.equals(e)). @param o element whose presence in this list is to be tested. @return true if this list contains the specified element. @throws ClassCastException if the type of the specified element is incompatible with this list (optional). @throws NullPointerException if the specified element is null and this list does not support null elements (optional).
Class List, boolean containsAll(Collection)

Returns true if this list contains all of the elements of the specified collection. @param c collection to be checked for containment in this list. @return true if this list contains all of the elements of the specified collection. @throws ClassCastException if the types of one or more elements in the specified collection are incompatible with this list (optional). @throws NullPointerException if the specified collection contains one or more null elements and this list does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see # contains(Object)
Class List, int indexOf(Object)

Returns the index in this list of the first occurrence of the specified element or -1 if this list does not contain this element. More formally returns the lowest index i such that (o==null get(i)==null : o.equals(get(i))) or -1 if there is no such index. @param o element to search for. @return the index in this list of the first occurrence of the specified element or -1 if this list does not contain this element. @throws ClassCastException if the type of the specified element is incompatible with this list (optional). @throws NullPointerException if the specified element is null and this list does not support null elements (optional).
Class List, int lastIndexOf(Object)

Returns the index in this list of the last occurrence of the specified element or -1 if this list does not contain this element. More formally returns the highest index i such that (o==null get(i)==null : o.equals(get(i))) or -1 if there is no such index. @param o element to search for. @return the index in this list of the last occurrence of the specified element or -1 if this list does not contain this element. @throws ClassCastException if the type of the specified element is incompatible with this list (optional). @throws NullPointerException if the specified element is null and this list does not support null elements (optional).
Class List, boolean remove(Object)

Removes the first occurrence in this list of the specified element (optional operation). If this list does not contain the element it is unchanged. More formally removes the element with the lowest index i such that (o==null get(i)==null : o.equals(get(i))) (if such an element exists). @param o element to be removed from this list if present. @return true if this list contained the specified element. @throws ClassCastException if the type of the specified element is incompatible with this list (optional). @throws NullPointerException if the specified element is null and this list does not support null elements (optional). @throws UnsupportedOperationException if the remove method is not supported by this list.
Class List, boolean removeAll(Collection)

Removes from this list all the elements that are contained in the specified collection (optional operation). @param c collection that defines which elements will be removed from this list. @return true if this list changed as a result of the call. @throws UnsupportedOperationException if the removeAll method is not supported by this list. @throws ClassCastException if the types of one or more elements in this list are incompatible with the specified collection (optional). @throws NullPointerException if this list 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 List, boolean retainAll(Collection)

Retains only the elements in this list that are contained in the specified collection (optional operation). In other words removes from this list all the elements that are not contained in the specified collection. @param c collection that defines which elements this set will retain. @return true if this list changed as a result of the call. @throws UnsupportedOperationException if the retainAll method is not supported by this list. @throws ClassCastException if the types of one or more elements in this list are incompatible with the specified collection (optional). @throws NullPointerException if this list 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 List, Object set(int, Object)

Replaces the element at the specified position in this list with the specified element (optional operation). @param index index of element to replace. @param element element to be stored at the specified position. @return the element previously at the specified position. @throws UnsupportedOperationException if the set method is not supported by this list. @throws ClassCastException if the class of the specified element prevents it from being added to this list. @throws NullPointerException if the specified element is null and this list does not support null elements. @throws IllegalArgumentException if some aspect of the specified element prevents it from being added to this list. @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index >= size()).
Class List, List subList(int, int)

Returns a view of the portion of this list between the specified 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 non-structural 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 passing 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 thisthe 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 this list or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.) @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 for an illegal endpoint index value (fromIndex < 0 || toIndex > size || fromIndex > toIndex).

Class List, Object[] toArray(Object[])

Returns an array containing all of the elements in this list in proper sequence; the runtime type of the returned array is that of the specified array. Obeys the general contract of the Collection.toArray(Object[]) method. @param a the array into which the elements of this 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 this list. @throws ArrayStoreException if the runtime type of the specified array is not a supertype of the runtime type of every element in this list. @throws NullPointerException if the specified array is null.

Class ListIterator

An iterator for lists that allows the programmer to traverse the list in either direction and modify the list during iteration and obtain the iterator's current position in the list. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). In a list of length n there are n+1 valid index values from 0 to n inclusive.
 Element(0) Element(1) Element(2) ... Element(n) ^ ^ ^ ^ ^ Index: 0 1 2 3 n+1 

Note that the #remove and #set(Object) methods are not defined in terms of the cursor position; they are defined to operate on the last element returned by a call to #next or #previous() @author Josh Bloch @version 1.16 0219 12/0203/0001 @see Collection @see List @see Iterator @see Enumeration @since 1.2

Class ListIterator, void add(Object)

Inserts the specified element into the list (optional operation). The element is inserted immediately before the next element that would be returned by next if any and after the next element that would be returned by previous if any. (If the list contains no elements the new element becomes the sole element on the list.) The new element is inserted before the implicit cursor: a subsequent call to next would be unaffected and a subsequent call to previous would return the new element. (This call increases by one the value that would be returned by a call to nextIndex or previousIndex.) @param o the element to insert. @exception UnsupportedOperationException if the add method is not supported by this list iterator. @exception ClassCastException if the class of the specified element prevents it from being added to this Setlist. @exception IllegalArgumentException if some aspect of this element prevents it from being added to this Collectionlist.

Class ListResourceBundle

ListResourceBundle is aan abstract subclass of ResourceBundle that manages resources for a locale in a convenient and easy to use list. See ResourceBundle for more information about resource bundles in general.

Subclasses must override getContents and provide an array where each item in the array is a pair of objects. The first element of each pair is the key which must be a String key and the second element is the value associated with that key. [Right

nowThe there'sfollowing noexample error-checkingshows code to enforce this so you could specifytwo members of a resource bundle family with key-valuethe pairsbase thatname "MyResources". have"MyResources" something other than a String as ais the default member of the bundle key.family Butand since"MyResources_fr" is the interfacesFrench member. These members are definedbased inon ListResourceBundle terms(a ofrelated Stringexample any valueshows how withyou can add a key thatbundle to isnthis family that't a String will bes based on a properties inaccessiblefile).] In the followingThe keys in this example the keys are of the form "s1".. etc. The actual keys are entirely up to your choice so long as they are the same as the keys you use in your program to retrieve the objects from the bundle. Keys are case-sensitive. MyResource is the default version of the bundle family and MyResource_fr is the french version:

 //====================public class MyResourceMyResources extends ListResourceBundle { public Object[][] getContents() { return contents; } static final Object[][] contents = { // LOCALIZE THIS {"s1" "3"} // starting value in choiceThe field {disk \"s2{1}\" "MyDiskcontains {0}."} // starting value in stringMessageFormat fieldpattern {"s3s2" "3 Mar 961"} // starting value in date field {"s4" "The disk '{1}'location containedof {0} on {2}."} // initialin pattern {"s5s3" "0My Disk"} // first choice numbersample disk name {"s6s4" "no files"} // first choice value {"s7" "1"} // secondChoiceFormat choice number {"s8s5" "one file"} // second choice value {"s9" "2"} // thirdChoiceFormat choice number {"s10s6" "{0 number}|3 files"} // third choice value {"s11" "format threw an exception: {0}"} // generic exception message {"s12" "ERROR"} // what to show in field in case of error {"s14"ChoiceFormat "Result"} // label for formatted stuffchoice {"s13s7" "Dialog"} // standard font3 {"s15"Mar "Pattern96"} // label for standardsample patterndate {"s16s8" new Dimension(1 5)} // real object not just string // END OF MATERIAL TO LOCALIZE }; } //====================public class MyResourceMyResources_fr extends ListResourceBundle { public Object[][] getContents() { return contents; } static final Object[][] contents = { // LOCALIZE THIS {"s1" "3"} // starting value in choice field {"s2" "MonDisk"} // starting value in string field {"s3" "3 Mar 96"} // starting value in date field {"s4" "Le diskdisque '\"{1}' a\" {0} a {2}."} // initialMessageFormat pattern {"s5s2" "01"} // first choicelocation numberof {"s6" "pas de files"0} // first choicein valuepattern {"s7s3" "1Mon disque"} // second choice numbersample disk name {"s8" s4"une file"} // secondne choice valuecontient pas {"s9"de "2fichiers"} // third choice numberfirst ChoiceFormat choice {"s10s5" "{0}|3contient filesun fichier"} // third choice valuesecond ChoiceFormat choice {"s11s6" "Le format acontient jete une exception: {0}"} // generic exception message {"s12" "ERROR"number} // what to show in field in case of error {"s14" fichiers"Resulte"} // label forthird formatted stuffChoiceFormat choice {"s13s7" "Dialogue"} // standard font3 {"s15"mars "Pattern1996"} // label for standardsample patterndate {"s16s8" new Dimension(1 3)} // real object not just string // END OF MATERIAL TO LOCALIZE }; } 
@see ResourceBundle @see PropertyResourceBundle @since JDK1.1

Class Locale

A Locale object represents a specific geographical political or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example displaying a number is a locale-sensitive operation--the number should be formatted according to the customs/conventions of the user's native country region or culture.

You createCreate a Locale object using one of the two constructors in this class:

 Locale(String language) Locale(String language String country) Locale(String language String country String variant) 
The firstlanguage argument to both constructors is a valid ISO Language Code. These codes are the lower-case two-letter codes as defined by ISO-639. You can find a full list of these codes at a number of sites such as:
http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt

The secondcountry argument to both constructors is a valid ISO Country Code. These codes are the upper-case two-letter codes as defined by ISO-3166. You can find a full list of these codes at a number of sites such as:
http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html

The second constructor requires a thirdvariant argument--the Variant. The Variant codes areis a vendor andor browser-specific code. For example use WIN for Windows MAC for Macintosh and POSIX for POSIX. Where there are two variants separate them with an underscore and put the most important one first. For example a Traditional Spanish collation might construct a locale with parameters for language country and variant as: "es" "ES" "Traditional_WIN".

Because a Locale object is just an identifier for a region no validity check is performed when you construct a Locale. If you want to see whether particular resources are available for the Locale you construct you must query those resources. For example ask the NumberFormat for the locales it supports using its getAvailableLocales method.
Note: When you ask for a resource for a particular locale you get back the best available match not necessarily precisely what you asked for. For more information look at ResourceBundle

The Locale class provides a number of convenient constants that you can use to create Locale objects for commonly used locales. For example the following creates a Locale object for the United States:

 Locale.US 

Once you've created a Locale you can query it for information about itself. Use getCountry to get the ISO Country Code and getLanguage to get the ISO Language Code. You can use getDisplayCountry to get the name of the country suitable for displaying to the user. Similarly you can use getDisplayLanguage to get the name of the language suitable for displaying to the user. Interestingly the getDisplayXXX methods are themselves locale-sensitive and have two versions: one that uses the default locale and one that uses the locale specified as an argument.

The Java 2 platform provides a number of classes that perform locale-sensitive operations. For example the NumberFormat class formats numbers currency or percentages in a locale-sensitive manner. Classes such as NumberFormat have a number of convenience methods for creating a default object of that type. For example the NumberFormat class provides these three convenience methods for creating a default NumberFormat object:

 NumberFormat.getInstance() NumberFormat.getCurrencyInstance() NumberFormat.getPercentInstance() 
These methods have two variants; one with an explicit locale and one without; the latter using the default locale.
 NumberFormat.getInstance(myLocale) NumberFormat.getCurrencyInstance(myLocale) NumberFormat.getPercentInstance(myLocale) 
A Locale is the mechanism for identifying the kind of object (NumberFormat) that you would like to get. The locale is just a mechanism for identifying objects not a container for the objects themselves.

Each class that performs locale-sensitive operations allows you to get all the available objects of that type. You can sift through these objects by language country or variant and use the display names to present a menu to the user. For example you can create a menu of all the collation objects suitable for a given language. Such classes must implement these three class methods:

 public static Locale[] getAvailableLocales() public static String getDisplayName(Locale objectLocale Locale displayLocale) public static final String getDisplayName(Locale objectLocale) // getDisplayName will throw MissingResourceException if the locale // is not one of the available locales. 
@see ResourceBundle @see java.text.Format @see java.text.NumberFormat @see java.text.Collator @version 1.55 0168 12/1903/0001 @author Mark Davis @since JDK11.1
Class Locale, constructor Locale(String, String)

Construct a locale from language country. To create a locale that only identifies a language use "" for the country. NOTE: ISO 639 is not a stable standard; some of the language codes it defines (specifically iw ji and in) have changed. This constructor accepts both the old codes (iw ji and in) and the new codes (he yi and id) but all other API on Locale will return only the OLD codes. @param language lowercase two-letter ISO-639 code. @param country uppercase two-letter ISO-3166 code. @exception NullPointerException thrown if either argument is null.
Class Locale, constructor Locale(String, String, String)

Construct a locale from language country variant. NOTE: ISO 639 is not a stable standard; some of the language codes it defines (specifically iw ji and in) have changed. This constructor accepts both the old codes (iw ji and in) and the new codes (he yi and id) but all other API on Locale will return only the OLD codes. @param language lowercase two-letter ISO-639 code. @param country uppercase two-letter ISO-3166 code. @param variant vendor and browser specific code. See class description. @exception NullPointerException thrown if any argument is null.
Class Locale, String getISO3Language()

Returns a three-letter abbreviation for this locale's language. If the locale doesn't specify a language this will be the empty string. Otherwise this will be a lowercase ISO 639-2/T language code. The ISO 639-2 language codes can be found on-line at http://www.triacom.com/archive/iso639-2.en.html and ftp://dkuug.dk/i18n/iso-639-2.txt @exception MissingResourceException Throws MissingResourceException if the three-letter language abbreviation is not available for this locale.
Class Locale, String toString()

Getter for the programmatic name of the entire locale with the language country and variant separated by underbars. Language is always lower case and country is always upper case. If the language is missing the string will begin with an underbar. If both the language and country fields are missing this function will return the empty string even if the variant field is filled in (you can't have a locale with just a variant-- the variant must accompany a valid language or country code). Examples: "en" "de_DE" "_GB" "en_US_WIN" "de__POSIX" "fr__MAC" @see #getDisplayName

Class Map

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

This interface takes the place of the Dictionary class which was a totally abstract class rather than an interface.

The Map interface provides three collection views which allow a map's contents to be viewed as a set of keys collection of values or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations like the TreeMap class make specific guarantees as to their order; others like the HashMap class do not.

Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value extreme caution is advised: the equals and hashCode methods are no longer well defined on a such a map.

All general-purpose map implementation classes should provide two "standard" constructors: a void (no arguments) constructor which creates an empty map and a constructor with a single argument of type Map which creates a new map with the same key-value mappings as its argument. In effect the latter constructor allows the user to copy any map producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the SDK comply.

The "destructive" methods contained in this interface that is the methods that modify the map on which they operate are specified to throw UnsupportedOperationException if this map 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 map. For example invoking the #putAll(Map) method on an unmodifiable map may but is not required to throw the exception if the map whose mappings are to be "superimposed" is empty.

Some map implementations have restrictions on the keys and values they may contain. For example some implementations prohibit null keys and values and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible key or value 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 key or value whose completion would not result in the insertion of an ineligible element into the map 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.32 0237 12/0203/0001 @see HashMap @see TreeMap @see Hashtable @see SortedMap @see Collection @see Set @since 1.2

Class Map, boolean containsKey(Object)

Returns true if this map contains a mapping for the specified key. More formally returns true if and only if this map contains at a mapping for a key k such that (key==null k==null : key.equals(k)). (There can be at most one such mapping.) @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 key is of an inappropriate type for this map (optional). @throws NullPointerException if the key is null and this map does not not permit null keys (optional).
Class Map, boolean containsValue(Object)

Returns true if this map maps one or more keys to the specified value. More formally returns true if and only if this map contains at least one mapping to a value v such that (value==null v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations of the Map interface. @param value value whose presence in this map is to be tested. @return true if this map maps one or more keys to the specified value. @throws ClassCastException if the value is of an inappropriate type for this map (optional). @throws NullPointerException if the value is null and this map does not not permit null values (optional).
Class Map, Set entrySet()

Returns a set view of the mappings contained in this map. Each element in the returned set is a Map.Entry. The set is backed by the map so changes to the map are reflected in the set and vice-versa. If the map is modified while an iteration over the set is in progress the results of the iteration are undefined. The set supports element removal which removes the corresponding mapping from the map via the Iterator.remove Set.remove removeAll retainAll and clear operations. It does not support the add or addAll operations. @return a set view of the mappings contained in this map.
Class Map, Object get(Object)

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.

More formally if this map contains a mapping from a key k to a value v such that (key==null k==null : key.equals(k)) then this method returns v; otherwise it returns null. (There can be at most one such mapping.) @param key key whose associated value is to be returned. @return the value to which this map maps the specified key or null if the map contains no mapping for this key. @throws ClassCastException if the key is of an inappropriate type for this map (optional). @throws NullPointerException key is null and this map does not not permit null keys (optional). @see #containsKey(Object)

Class Map, Object put(Object, Object)

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for this key the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)) @param key key with which the specified value is to be associated. @param value value to be associated with the specified key. @return previous value associated with specified key or null if there was no mapping 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 put operation is not supported by this map. @throws ClassCastException if the class of the specified key or value prevents it from being stored in this map. @throws IllegalArgumentException if some aspect of this key or value prevents it from being stored in this map. @throws NullPointerException this map does not permit null keys or values and the specified key or value is null.
Class Map, void putAll(Map)

Copies all of the mappings from the specified map to this map (optional operation). TheseThe mappingseffect of will replace any mappingsthis call is equivalent to that of calling Object put(k v)} on this map hadonce for anyeach of themapping from keyskey k to currentlyvalue v in the specified map. The behavior of this operation is unspecified if the specified map is modified while the operation is in progress. @param t Mappings to be stored in this map. @throws UnsupportedOperationException if the putAll method 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 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 valuemap iscontains null keys or values.
Class Map, Object remove(Object)

Removes the mapping for this key from this map if it is present (optional operation). @paramMore formally if this map contains a mapping from key k to value v such that (key==null k==null : key.equals(k)) whosethat mapping is toremoved. be(The removed from themap can contain mapat most one such mapping.) @return

Returns previousthe value associatedto withwhich specifiedthe map previously associated the key or null if therethe wasmap contained no mapping for this key. (A null return can also indicate that the map previously associated null with the specified key if the implementation supports null values.) The map will not contain a mapping for the specified key once the call returns. @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 mapping for key. @throws ClassCastException if the key is of an inappropriate type for this map (optional). @throws NullPointerException if the key is null and this map does not not permit null keys (optional). @throws UnsupportedOperationException if the remove method is not supported by this map.


Class MissingResourceException

Signals that a resource is missing. @see java.lang.Exception @see ResourceBundle @version 1.12 0114 12/1903/0001 @author Mark Davis @since JDK1.1
Class MissingResourceException, constructor MissingResourceException(String, String, String)

Constructs a MissingResourceException with the specified information. A detail message is a String that describes this particular exception. @param s the detail message @param classnameclassName the name of the resource class @param key the key for the missing resource.
Class MissingResourceException, String getClassName()

Gets parameter passed by constructor. @return the name of the resource class
Class MissingResourceException, String getKey()

Gets parameter passed by constructor. @return the key for the missing resource

Class NoSuchElementException

Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration. @author unascribed @version 1.18 0219 12/0203/0001 @see java.util.Enumeration @see java.util.Enumeration#nextElement() @since JDK1.0

Class Observable

This class represents an observable object or "data" in the model-view paradigm. It can be subclassed to represent an object that the application wants to have observed.

An observable object can have one or more observers. An observer may be any object that implements interface Observer. After an observable instance changes an application calling the Observable's notifyObservers method causes all of its observers to be notified of the change by a call to their update method.

The order in which notifications will be delivered is unspecified. The default implementation provided in the Observerable class will notify Observers in the order in which they registered interest but subclasses may change this order use no guaranteed order deliver notifications on separate threaadsthreads or may guarantee that their subclass follows this order as they choose.

Note that this notification mechanism is has nothing to do with threads and is completely separate from the wait and notify mechanism of class Object.

When an observable object is newly created its set of observers is empty. Two observers are considered the same if and only if the equals method returns true for them. @author Chris Warth @version 1.3134 0212/0203/0001 @see java.util.Observable#notifyObservers() @see java.util.Observable#notifyObservers(java.lang.Object) @see java.util.Observer @see java.util.Observer#update(java.util.Observable java.lang.Object) @since JDK1.0

Class Observable, void addObserver(Observer)

Adds an observer to the set of observers for this object provided that it is not the same as some observer already in the set. The order in which notifications will be delivered to multiple observers is not specified. See the class comment. @param o an observer to be added. @throws NullPointerException if the parameter o is null.

Class Observer

A class can implement the Observer interface when it wants to be informed of changes in observable objects. @author Chris Warth @version 1.16 0217 12/0203/0001 @see java.util.Observable @since JDK1.0

Class Properties

The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.

A property list can contain another property list as its "defaults"; this second property list is searched if the property key is not found in the original property list.

Because Properties inherits from Hashtable the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If the store or save method is called on a "compromised" Properties object that contains a non-String key or value the call will fail.

When saving properties to a stream or loading them from a stream the ISO 8859-1 character encoding is used. For characters that cannot be directly represented in this encoding Unicode escapes are used; however only a single 'u' character is allowed in an escape sequence. The native2ascii tool can be used to convert property files to and from other character encodings. @see native2ascii tool for Solaris @see native2ascii tool for Windows @author Arthur van Hoff @author Michael McCloskey @version 1.60 0264 06/0226/00 @since JDK1.0

Class Properties, Enumeration propertyNames()

Returns an enumeration of all the keys in this property list including thedistinct keys in the default property list if a key of the same name has not already been found from the main properties list. @return an enumeration of all the keys in this property list including the keys in the default property list. @see java.util.Enumeration @see java.util.Properties#defaults
Class Properties, Object setProperty(String, String)

Calls the hashtableHashtable method put. Provided for parallelism with the getProperty method. Enforces use of strings for property keys and values. The value returned is the result of the Hashtable call to put. @param key the key to be placed into this property list. @param value the value corresponding to key. @return the previous value of the specified key in this property list or null if it did not have one. @see #getProperty @since 1.2
Class Properties, void store(OutputStream, String)

Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the load method. The stream is written using the ISO 8859-1 character encoding.

Properties from the defaults table of this Properties table (if any) are not written out by this method.

If the header argument is not null then an ASCII # character the header string and a line separator are first written to the output stream. Thus the header can serve as an identifying comment.

Next a comment line is always written consisting of an ASCII # character the current date and time (as if produced by the toString method of Date for the current time) and a line separator as generated by the Writer.

Then every entry in this Properties table is written out one per line. For each entry the key string is written then an ASCII = then the associated element string. Each character of the element string is examined to see whether it should be rendered as an escape sequence. The ASCII characters \ tab newline and carriage return are written as \\ \t \n and \r respectively. Characters less than \u0020 and characters greater than \u007E are written as \uxxxx for the appropriate hexadecimal value xxxx. Leading space characters but not embedded or trailing space characters are written with a preceding \. The key and value characters # = and : are written with a preceding slash to ensure that they are properly loaded.

After the entries have been written the output stream is flushed. The output stream remains open after this method returns. @param out an output stream. @param header a description of the property list. @exception IOException if writing this property list to the specified output stream throws an IOException. @exception ClassCastException if this Properties object contains any keys or values that are not Strings. @exception NullPointerException if out is null. @since 1.2


Class PropertyPermission

This class is for property permissions.

The name is the name of the property ("java.home" "os.name" etc). The naming convention follows the hierarchical property naming convention. Also an asterisk may appear at the end of the name following a "." or by itself to signify a wildcard match. For example: "java.*" or "*" is valid "*java" or "a*b" is not valid.

The actions to be granted are passed to the constructor in a string containing a list of zero or more comma-separated keywords. The possible keywords are "read" and "write". Their meaning is defined as follows:

read
read permission. Allows System.getProperty to be called.
write
write permission. Allows System.setProperty to be called.

The actions string is converted to lowercase before processing.

Care should be taken before granting code permission to access certain system properties. For example granting permission to access the "java.home" system property gives potentially malevolent code sensitive information about the system environment (the Java installation directory). Also granting permission to access the "user.name" and "user.home" system properties gives potentially malevolent code sensitive information about the user environment (the user's account name and home directory). @see java.security.BasicPermission @see java.security.Permission @see java.security.Permissions @see java.security.PermissionCollection @see java.lang.SecurityManager @version 1.24 0027 01/0212/0203 @author Roland Schemers @since 1.2 @serial exclude

Class PropertyPermission, boolean implies(Permission)

Checks if this PropertyPermission object "implies" the specified permission.

More specifically this method returns true if:

@param p the permission to check against. @return true if the specified permission is implied by this object false if not.

Class PropertyResourceBundle

PropertyResourceBundle is a concrete subclass of ResourceBundle that manages resources for a locale using a set of static strings from a property file. See ResourceBundle for more information about resource bundles. See Properties for more information about properties files in particular the information on character encodings.

Unlike other types of resource bundle you don't subclass PropertyResourceBundle. Instead you supply properties files containing the resource data. ResourceBundle.getBundle() will automatically look for the appropriate properties file and create a PropertyResourceBundle that refers to it. The resource bundle name that youSee passjava.util.Local tojava.lang.ClassLoader) ResourceBundle.getBundle()} is the file namefor a complete description of the propertiessearch file notand instantiation thestrategy. class name of

The following theexample object that isshows a member returned.of For example if you saya resource bundle family with the ResourceBundle.getBundle(base name "MyResources". newThe Locale("fr"text "FR"));defines the resource bundle lookup"MyResources_de" mechanism willthe German searchmember of the classbundle pathfamily. for a fileThis member is calledbased on MyResources_fr_FR.propertiesPropertyResourceBundle. If a real class and aand the text therefore is the content propertiesof the file with"MyResources_de.properties" (a particular name both exist the classrelated wins;example the properties file will only be used if there is no class with the desiredshows how you can add bundles to this family that are implemented as subclasses of nameListResourceBundle). In the followingThe keys in this example the keys are of the form "s1".. etc. The actual keys are entirely up to your choice so long as they are the same as the keys you use in your program to retrieve the objects from the bundle. Keys are case-sensitive.

 s1=3 s2=MeinDisk s3=3# Mar 96 s4MessageFormat pattern s1=DerDie diskPlatte '\"{1}'\" aenthält {0}. a# {2}.location s5=of {0} s6=keinein Datein s7pattern s2=1 s8=ein# Dateisample disk name s9s3=2Meine Platte # first ChoiceFormat choice s10s4={0}|3keine Dateien Datein# s11second ChoiceFormat choice s5=Dereine Datei Format worf ein# third ChoiceFormat Exception:choice s6={0 number} s12=ERRORDateien s14=Resulte# s13=Dialoguesample s15=Patterndate s16s7=1 3. März 1996 
@see ResourceBundle @see ListResourceBundle @see Properties @since JDK1.1
Class PropertyResourceBundle, constructor PropertyResourceBundle(InputStream)

Creates a property resource bundle. @param stream property file to read from.

Class Random

An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed which is modified using a linear congruential formula. (See Donald Knuth The Art of Computer Programming Volume 2 Section 3.2.1.)

If two instances of Random are created with the same seed and the same sequence of method calls is made for each they will generate and return identical sequences of numbers. In order to guarantee this property particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random for the sake of absolute portability of Java code. However subclasses of class Random are permitted to use other algorithms so long as they adhere to the general contracts for all the methods.

The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.

Many applications will find the random method in class Math simpler to use. @author Frank Yellin @version 1.34 0236 12/0203/0001 @see java.lang.Math#random() @since JDK1.0

Class Random, constructor Random()

Creates a new random number generator. Its seed is initialized to a value based on the current time:
 public Random() { this(System.currentTimeMillis()); }
Two Random objects created within the same millisecond will have the same sequence of random numbers. @see java.lang.System#currentTimeMillis()

Class ResourceBundle

Resource bundles contain locale-specific objects. When your program needs a locale-specific resource a String for example your program can load it from the resource bundle that is appropriate for the current user's locale. In this way you can write program code that is largely independent of the user's locale isolating most if not all of the locale-specific information in resource bundles.

This allows you to write programs that can:

One resource bundle is conceptually a set of related classesResource that inherit frombundles belong to ResourceBundle.families Each related subclass ofwhose members share a ResourceBundlecommon has the same base name plus anbase name but whose names also have additional componentcomponents that identifies its localeidentify their locales. For example supposethe your resource bundle is namedbase name of a family MyResources.of The first class youresource bundles might be are"MyResources". likely to write is theThe family should have a default resource bundle which simply has the same name as its family- - "MyResources" - and will be used as the bundle of last resort if a specific locale is not supported. YouThe family can alsothen provide as many related locale-specific classesmembers as you need:needed for example perhaps you would provide a German one named "MyResources_de".

Each related subclass ofresource bundle in ResourceBundlea family contains the same items but the items have been translated for the locale represented by that ResourceBundleresource subclassbundle. For example both "MyResources" and "MyResources_de" may have a String that's used on a button for canceling operations. In "MyResources" the String may contain "Cancel" and in "MyResources_de" it may contain "Abbrechen".

If there are different resources for different countries you can make specializations: for example "MyResources_de_CH" iscontains objects for the German language (de) in Switzerland (CH). If you want to only modify some of the resources in the specialization you can do so.

When your program needs a locale-specific object it loads the ResourceBundle class using the java.util.Locale getBundle} method:

 ResourceBundle myResources = ResourceBundle.getBundle("MyResources" currentLocale); 
The first argument specifies the family name of the resource bundle that contains the object in question. The second argument indicates the desired locale. getBundle uses these two arguments to construct the name of the ResourceBundle subclass it should load as follows. The resource bundle lookup searches for classes with various suffixes on the basis of (1) the desired locale and (2) the current default locale as returned by Locale.getDefault() and (3) the root resource bundle (baseclass) in the following order from lower-level (more specific) to parent-level (less specific): baseclass + "_" + language1 + "_" + country1 + "_" + variant1 baseclass + "_" + language1 + "_" + country1 + "_" + variant1 + ".properties" baseclass + "_" + language1 + "_" + country1 baseclass + "_" + language1 + "_" + country1 + ".properties" baseclass + "_" + language1 baseclass + "_" + language1 + ".properties" baseclass + "_" + language2 + "_" + country2 + "_" + variant2 baseclass + "_" + language2 + "_" + country2 + "_" + variant2 + ".properties" baseclass + "_" + language2 + "_" + country2 baseclass + "_" + language2 + "_" + country2 + ".properties" baseclass + "_" + language2 baseclass + "_" + language2 + ".properties" baseclass baseclass + ".properties" For example if the current default locale is en_US the locale the caller is interested in is fr_CH and the resource bundle name is MyResources resource bundle lookup will search for the following classes in order: MyResources_fr_CH MyResources_fr MyResources_en_US MyResources_en MyResources The result of the lookup is a class but that class may be backed by a properties file on disk. That is if getBundle does not find a class of a given name it appends ".properties" to the class name and searches for a properties file of that name. If it finds such a file it creates a new PropertyResourceBundle object to hold it. Following on the previous example it will return classes and and files giving preference as follows: (class) MyResources_fr_CH (file) MyResources_fr_CH.properties (class) MyResources_fr (file) MyResources_fr.properties (class) MyResources_en_US (file) MyResources_en_US.properties (class) MyResources_en (file) MyResources_en.properties (class) MyResources (file) MyResources.properties If a lookup fails getBundle() throws a MissingResourceException. The baseclass must be fully qualified (for example myPackage.MyResources not just MyResources). It must also be accessable by your code; it cannot be a class that is private to the package where ResourceBundle.getBundle is called. Note: ResourceBundles are used internally in accessing NumberFormats Collations and so on. The lookup strategy is the same.

Resource bundles contain key/value pairs. The keys uniquely identify a locale-specific object in the bundle. Here's an example of a ListResourceBundle that contains two key/value pairs:

 public class MyResourceMyResources extends ListResourceBundle { public Object[][] getContents() { return contents; } static final Object[][] contents = { // LOCALIZE THIS {"OkKey" "OK"} {"CancelKey" "Cancel"} // END OF MATERIAL TO LOCALIZE }; } 
Keys are always Strings. In this example the keys are "OkKey" and "CancelKey". In the above example the values are also Strings--"OK" and "Cancel"--but they don't have to be. The values can be any type of object.

You retrieve an object from resource bundle using the appropriate getter method. Because "OkKey" and "CancelKey" are both strings you would use getString to retrieve them:

 button1 = new Button(myResourceBundlemyResources.getString("OkKey")); button2 = new Button(myResourceBundlemyResources.getString("CancelKey")); 
The getter methods all require the key as an argument and return the object if found. If the object is not found the getter method throws a MissingResourceException.

Besides getString; ResourceBundle supports a numberalso of other methodsprovides a method for getting different types of objectsstring sucharrays as getStringArray. If youas well don'tas have ana generic objectgetObject that matches one of these methodsmethod for any other type of youobject. can useWhen using getObject andyou'll have to cast the result to the appropriate type. For example:

 int[] myIntegers = (int[]) myResources.getObject("intList"); 

NOTE: You should always supply a baseclass with no suffixes. This will be the class of "last resort" if a locale is requested that does not exist. In fact you must provide all of the classes in any given inheritance chain that you provide a resource for. For example if you provide MyResources_fr_BE you must provide both MyResources and MyResources_fr or the resource bundle lookup won't work right. The Java 2 platform provides two subclasses of ResourceBundle ListResourceBundle and PropertyResourceBundle that provide a fairly simple way to create resources. (Once serialization is fully integrated we will provide another way.) As you saw briefly in a previous example ListResourceBundle manages its resource as a List of key/value pairs. PropertyResourceBundle uses a properties file to manage its resources.

If ListResourceBundle or PropertyResourceBundle do not suit your needs you can write your own ResourceBundle subclass. Your subclasses must override two methods: handleGetObject and getKeys().

The following is a very simple example of a ResourceBundle subclass MyResources that manages two resources (for a larger number of resources you would probably use a Hashtable). Notice that if the key is not found handleGetObject must return null. If the key is null a NullPointerException should be thrown. Notice also that you don't need to supply a value if a "parent-level" ResourceBundle handles the same key with the same value (as in United Kingdomfor the okKey below). Also notice that because you specify an en_GB resource bundle you also have to provide a default en resource bundle even though it inherits all its data from the root resource bundle.

Example:

 // default (English language United States) abstractpublic class MyResources extends ResourceBundle { public Object handleGetObject(String key) { if (key.equals("okKey")) return "Ok"; if (key.equals("cancelKey")) return "Cancel"; return null; } } // German language public class MyResources_de extends MyResources { public Object handleGetObject(String key) { // don't need okKey since parent level handles it. if (key.equals("cancelKey")) return "Abbrechen"; return null; } } 
You do not have to restrict yourself to using a single family of ResourceBundles. For example you could have a set of bundles for exception messages ExceptionResources (ExceptionResources_fr ExceptionResources_de ...) and one for widgets WidgetResource (WidgetResources_fr WidgetResources_de ...); breaking up the resources however you like. @see ListResourceBundle @see PropertyResourceBundle @see MissingResourceException @since JDK1.1
Class ResourceBundle, ResourceBundle getBundle(String)

GetGets a resource bundle using the specified base name the default locale and the caller's class loader. Calling this method is equivalent to calling
getBundle(baseName Locale.getDefault() this.getClass().getClassLoader())
except that getClassLoader() is run with
the appropriatesecurity privileges of ResourceBundle. See java.util.Local java.lang.ClassLoader) getBundle} for a complete description subclassof the search and instantiation strategy. @param baseName seethe base name of the resource bundle a fully qualified class descriptionname @exception java.lang.NullPointerException if baseName is null @exception MissingResourceException if no resource bundle for the specified base name can be found @return a resource bundle for the given base name and the default locale
Class ResourceBundle, ResourceBundle getBundle(String, Locale)

GetGets a resource bundle using the specified base name and locale and the caller's class loader. Calling this method is equivalent to calling
getBundle(baseName locale this.getClass().getClassLoader())
except that getClassLoader() is run with
the appropriatesecurity privileges of ResourceBundle. See java.util.Local subclassjava.lang.ClassLoader) getBundle} for a complete description of the search and instantiation strategy. @param baseName seethe base name of the resource bundle a fully qualified class description.name @param locale see classthe locale descriptionfor which a resource bundle is desired @exception java.lang.NullPointerException if baseName or locale is null @exception MissingResourceException if no resource bundle for the specified base name can be found @return a resource bundle for the given base name and locale
Class ResourceBundle, Enumeration getKeys()

ReturnReturns an enumeration of the keys. NOTE: Subclasses must override.
Class ResourceBundle, Locale getLocale()

ReturnReturns the Localelocale forof this ResourceBundleresource bundle. (This functionmethod can be used after a call to getBundle() to determine whether the ResourceBundleresource bundle returned really corresponds to the requested locale or is a fallback.) @return the locale of this resource bundle
Class ResourceBundle, Object getObject(String)

GetGets an object for the given key from this resource bundle or one of its parents. This method first tries to obtain the object from this resource bundle using handleGetObject If not successful and the parent resource bundle is not null it calls the parent's getObject method. If still not successful it throws a ResourceBundleMissingResourceException. @param key seethe classkey description.for the desired object @exception NullPointerException if key is null. @exception MissingResourceException if no object for the given key can be found @return the object for the given key
Class ResourceBundle, String getString(String)

Get anGets a objectstring for the given key from athis resource bundle ResourceBundleor one of its parents. ConvenienceCalling this method is equivalent to savecalling casting.
(String) getObject}(key)
@param key seethe key for classthe description.desired string @exception NullPointerException if key is null. @exception MissingResourceException if no object for the given key can be found @exception ClassCastException if the object found for the given key is not a string @return the string for the given key
Class ResourceBundle, String[] getStringArray(String)

Get anGets a objectstring array for the given key from athis resource bundle ResourceBundleor one of its parents. ConvenienceCalling this method is equivalent to savecalling casting.
(String[]) getObject}(key)
@param key seethe key for classthe description.desired string array @exception NullPointerException if key is null. @exception MissingResourceException if no object for the given key can be found @exception ClassCastException if the object found for the given key is not a string array @return the string array for the given key
Class ResourceBundle, Object handleGetObject(String)

GetGets an object for the given key from athis resource ResourceBundlebundle. NOTE:Returns null if this resource bundle does not contain an object for Subclassesthe must overridegiven key. @param key seethe classkey description.for the desired object @exception NullPointerException if key is null. @return the object for the given key or null
Class ResourceBundle, void setParent(ResourceBundle)

SetSets the parent bundle of this bundle. The parent bundle is searched by getObject when this bundle does not contain a particular resource. @param parent this bundle's parent bundle.
Class ResourceBundle, ResourceBundle parent

The parent bundle of this bundle. The parent bundle is consultedsearched by getObject when this bundle does not contain a particular resource.

Class Set

A collection that contains no duplicate elements. More formally sets contain no pair of elements e1 and e2 such that e1.equals(e2) and at most one null element. As implied by its name this interface models the mathematical set abstraction.

The Set interface places additional stipulations beyond those inherited from the Collection interface on the contracts of all constructors and on the contracts of the add equals and hashCode methods. Declarations for other inherited methods are also included here for convenience. (The specifications accompanying these declarations have been tailored to the Set interface but they do not contain any additional stipulations.)

The additional stipulation on constructors is not surprisingly that all constructors must create a set that contains no duplicate elements (as defined above).

Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.

Some set 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 set 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.23 0227 12/0203/0001 @see Collection @see List @see SortedSet @see HashSet @see TreeSet @see AbstractSet @see Collections#singleton(java.lang.Object) @see Collections#EMPTY_SET @since 1.2

Class Set, boolean add(Object)

Adds the specified element to this set if it is not already present (optional operation). More formally adds the specified element o to this set if this set contains no element e such that (o==null e==null : o.equals(e)). If this set already contains the specified element the call leaves this set unchanged and returns false. In combination with the restriction on constructors this ensures that sets never contain duplicate elements.

The stipulation above does not imply that sets must accept all elements; sets may refuse to add any particular element including null and throwing an exception as described in the specification for Collection.add. Individual set implementations should clearly document any restrictions on the the elements that they may contain. @param o element to be added to this set. @return true if this set did not already contain the specified element. @throws UnsupportedOperationException if the add method is not supported by this set. @throws ClassCastException if the class of the specified element prevents it from being added to this set. @throws NullPointerException if the specified element is null and this set does not support null elements. @throws IllegalArgumentException if some aspect of thisthe specified element prevents it from being added to this set.

Class Set, boolean addAll(Collection)

Adds all of the elements in the specified collection to this set if they're not already present (optional operation). If the specified collection is also a set the addAll operation effectively modifies this set so that its value is the union of the two sets. The behavior of this operation is unspecified if the specified collection is modified while the operation is in progress. @param c collection whose elements are to be added to this set. @return true if this set changed as a result of the call. @throws UnsupportedOperationException if the addAll method is not supported by this set. @throws ClassCastException if the class of some element of the specified collection prevents it from being added to this set. @throws NullPointerException if the specified collection contains one or more null elements and this set does not support null elements or if the specified collection is null. @throws IllegalArgumentException if some aspect of some element of the specified collection prevents it from being added to this set. @see #add(Object)
Class Set, boolean contains(Object)

Returns true if this set contains the specified element. More formally returns true if and only if this set contains an element e such that (o==null e==null : o.equals(e)). @param o element whose presence in this set is to be tested. @return true if this set contains the specified element. @throws ClassCastException if the type of the specified element is incompatible with this set (optional). @throws NullPointerException if the specified element is null and this set does not support null elements (optional).
Class Set, boolean containsAll(Collection)

Returns true if this set contains all of the elements of the specified collection. If the specified collection is also a set this method returns true if it is a subset of this set. @param c collection to be checked for containment in this set. @return true if this set contains all of the elements of the specified collection. @throws ClassCastException if the types of one or more elements in the specified collection are incompatible with this set (optional). @throws NullPointerException if the specified collection contains one or more null elements and this set does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #contains(Object)
Class Set, boolean remove(Object)

Removes the specified element from this set if it is present (optional operation). More formally removes an element e such that (o==null e==null : o.equals(e)) if the set contains such an element. Returns true if the set contained the specified element (or equivalently if the set changed as a result of the call). (The set will not contain the specified element once the call returns.) @param o object to be removed from this set if present. @return true if the set contained the specified element. @throws ClassCastException if the type of the specified element is incompatible with this set (optional). @throws NullPointerException if the specified element is null and this set does not support null elements (optional). @throws UnsupportedOperationException if the remove method is not supported by this set.
Class Set, boolean removeAll(Collection)

Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets. @param c collection that defines which elements will be removed from this set. @return true if this set 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 set are incompatible with the specified collection (optional). @throws NullPointerException if this set contains a null element and the specified collection does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #remove(Object)
Class Set, boolean retainAll(Collection)

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set this operation effectively modifies this set so that its value is the intersection of the two sets. @param c collection that defines which elements this set will retain. @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 set are incompatible with the specified collection (optional). @throws NullPointerException if this set contains a null element and the specified collection does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #remove(Object)
Class Set, Object[] toArray(Object[])

Returns an array containing all of the elements in this set; whosethe runtime type of the returned array is that of the specified array. Obeys the general contract of the Collection.toArray(Object[]) method. @param a the array into which the elements of this set 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 set. @throws ArrayStoreException the runtime type of a is not a supertype of the runtime type of every element in this set. @throws NullPointerException if the specified array is null.

Class SimpleTimeZone

SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone for use with a Gregorian calendar. ThisThe class doesholds notan offset from GMT called raw offset and start and end rules for a daylight saving time schedule. Since it only holds single values for each it cannot handle historical changes. Use a negative value forin the offset from GMT and dayOfWeekInMonththe todaylight saving indicateschedule except that the setStartYear method can specify the year when the daylight saving time schedule starts in effect.

To construct a SimpleTimeZone should count fromwith a daylight saving time schedule the schedule can be described with a set of rules start-rule and end-rule. A day when daylight saving time starts or ends is specified by a combination of month day-of-month and day-of-week values. The month value is represented by a Calendar MONTH field value such as Calendar#MARCH The day-of-week value is represented by a Calendar DAY_OF_WEEK value such as SUNDAY The meanings of value combinations are as follows.

The time of the day at which daylight saving time starts or ends is specified by a
backwardsmillisecond value within the day. There are three kinds of modes to specify the time: #WALL_TIME #STANDARD_TIME and #UTC_TIME For example Daylightif daylight saving time ends at 2:00 am in the wall clock time it can be specified by 7200000 milliseconds in the #WALL_TIME mode. In this case the wall clock time for an end-rule means the same thing as the daylight time.

The Savings Timefollowing are examples of parameters for constructing time zone objects.

 // Base GMT offset: -8:00 // DST starts: at 2:00am in standard time // on the first Sunday in April // DST ends: at 2:00am in daylight time // on the last Sunday in October // Save: 1 hour SimpleTimeZone(dayOfWeekInMonth-28800000 "America/Los_Angeles" Calendar.APRIL 1 -Calendar.SUNDAY =7200000 Calendar.OCTOBER -1 Calendar.SUNDAY 7200000 3600000) // Base GMT offset: +1:00 // DST starts: at 1:00am in UTC time // on the last Sunday in OctoberMarch at// 2DST ends: AMat 1:00am in standardUTC time // on the last Sunday in October // Save: 1 hour SimpleTimeZone(3600000 "Europe/Paris" Calendar.MARCH -1 Calendar.SUNDAY 3600000 SimpleTimeZone.UTC_TIME Calendar.OCTOBER -1 Calendar.SUNDAY 3600000 SimpleTimeZone.UTC_TIME 3600000) 
These parameter rules are also applicable to the set rule methods such as setStartRule. @since 1
.1 @see Calendar @see GregorianCalendar @see TimeZone @version 1.38 0143 12/1903/0001 @author David Goldsmith Mark Davis Chen-Lieh Huang Alan Liu
Class SimpleTimeZone, constructor SimpleTimeZone(int, String)

Constructs a SimpleTimeZone with the given base time zone offset from GMT and time zone ID. Timezone IDs can be obtained from TimeZone.getAvailableIDs. Normally you should usewith TimeZone.getDefaultno to construct a TimeZonedaylight saving time schedule. @param rawOffset The given base time zone offset in milliseconds to GMT. @param ID The time zone ID whichname that is obtainedgiven fromto TimeZone.getAvailableIDsthis instance.
Class SimpleTimeZone, constructor SimpleTimeZone(int, String, int, int, int, int, int, int, int, int)

ConstructConstructs a SimpleTimeZone with the given base time zone offset from GMT time zone ID timeand torules startfor starting and endending the daylight time. Timezone IDs can be obtained from TimeZone.getAvailableIDs.Both NormallystartTime youand shouldendTime useare TimeZone.getDefaultspecified to create a TimeZone. For a time zone that does not use daylight saving time do not use this constructor; instead you should use SimpleTimeZone(rawOffset ID). By default this constructorbe specifiesrepresented day-of-week-in-month rules. That is if the startDay is 1 and the startDayOfWeek is SUNDAY then this indicates the first Sunday inwall the startMonthclock time. AThe startDayamount of -1 likewise indicates the last Sunday. However by using negative or zero values for certain parameters otherdaylight types of rules cansaving is assumed to be specified. Day of month. To specify an exact day of the month such as March 13600000 set startDayOfWeek tomilliseconds zero(i. Day of week after day of monthe. To specify the first day of the week occurring on or after an exact day of the month make the day of theone week negativehour). For example if startDay isThis 5 and startDayOfWeekconstructor is -MONDAY this indicates the first Mondayequivalent on or after the 5thto: day
 ofSimpleTimeZone(rawOffset theID startMonth. Day of week before day of month. To specify the last day of the week occurring on or before an exact day of the month make the day of the week and the day of the month negative. For example if startDay is -21 and startDayOfWeek is -WEDNESDAY this indicates the last Wednesday on or before the 21st of thestartTime startMonthSimpleTimeZone. The above examples refer to the startMonth startDay and startDayOfWeek;{@link the#WALL_TIME} same applies for theendMonth endDay endDayOfWeek endTime endMonthSimpleTimeZone.{@link endDay#WALL_TIME} and3600000) endDayOfWeek.
@param rawOffset The given base time zone offset tofrom GMT. @param ID The time zone ID which is obtainedgiven to fromthis TimeZone.getAvailableIDsobject. @param startMonth The daylight savingssaving time starting month. Month is a MONTH field value (0-based. ege.g. 0 for January). @param startDay The daylight savings startingday of the day-of-week-in-month. on which the daylight saving Pleasetime starts. seeSee the memberclass description for anthe special examplecases of this parameter. @param startDayOfWeek The daylight savingssaving time starting day-of-week. Please seeSee the memberclass description for anthe special cases of examplethis parameter. @param startTime The daylight savingssaving time starting time in local wall clock time (in milliseconds within the day) which is local standard time in this case. Please see the member description for an example. @param endMonth The daylight savingssaving time ending month. Month is a MONTH field value (0-based. ege.g. 09 for JanuaryOctober). @param endDay The daylight savings endingday of the day-of-week-in-month. on which the daylight saving time Pleaseends. seeSee the memberclass description for anthe special cases of this exampleparameter. @param endDayOfWeek The daylight savingssaving time ending day-of-week. PleaseSee see the memberclass description for anthe special cases exampleof this parameter. @param endTime The daylight savingssaving ending time in local wall clock time (in milliseconds within the day) which is local daylight time in this case. Please see the member description for an example. @exception IllegalArgumentException if the month day dayOfWeek or time parameters are out of range for the start or end rule @since JDK1.1
Class SimpleTimeZone, constructor SimpleTimeZone(int, String, int, int, int, int, int, int, int, int, int)

ConstructorConstructs a SimpleTimeZone with the given base time zone offset from GMT time zone ID and rules for starting and ending the daylight time. Both startTime and endTime are assumed to be represented in the wall clock time. This constructor is identicalequivalent to:
 SimpleTimeZone(rawOffset ID startMonth startDay startDayOfWeek startTime SimpleTimeZone.{@link #WALL_TIME} endMonth endDay endDayOfWeek endTime SimpleTimeZone.{@link #WALL_TIME} dstSavings) 
@param rawOffset The given base time zone offset from GMT. @param ID The time zone ID which is given
to this object. @param startMonth The daylight saving time starting month. Month is a MONTH field value (0-based. e.g. 0 for January). @param startDay The day of the month on which the daylight saving time starts. See the class description for the 10special cases of this parameter. @param startDayOfWeek The daylight saving time starting day-of-argumentweek. constructorSee the class description for the special cases of this parameter. @param startTime The daylight saving time starting time in local wall clock time which is local standard buttime in this case. @param endMonth The also takesdaylight saving time ending month. Month is a dstSavingsMONTH field value (0-based. e.g. 9 for October). @param endDay The day of the month on which the daylight saving time ends. See the class description for the special cases of this parameter. @param endDayOfWeek The daylight saving time ending day-of-week. See the class description for the special cases of this parameter. @param endTime The daylight saving ending time in local wall clock time which is local daylight time in this case. @param dstSavings The amount of time in msmilliseconds saved during DSTdaylight saving time. @exception IllegalArgumentException if the month day dayOfWeek or time parameters are out of range for the start or end rule @since 1.2
Class SimpleTimeZone, Object clone()

OverridesReturns Cloneablea clone of this SimpleTimeZone instance. @return a clone of this instance.
Class SimpleTimeZone, boolean equals(Object)

Compares the equality of two SimpleTimeZone objects. @param obj The SimpleTimeZone object to be compared with. @return True if the given obj is the same as this SimpleTimeZone object; false otherwise.
Class SimpleTimeZone, int getDSTSavings()

Returns the amount of time in msmilliseconds that the clock is advanced during DSTdaylight saving time. @return the number of milliseconds the time is advanced with respect to standard time when the daylight savingssaving rules are in effect. A positiveor 0 number(zero) typically one hourif this time (3600000)zone doesn't observe daylight saving time. @see #setDSTSavings @since 1.2
Class SimpleTimeZone, int getOffset(int, int, int, int, int, int)

Returns the difference in milliseconds between local time and UTC taking into account both the raw offset and the effect of daylight savingssaving for the specified date and time. This method assumes that the start and end month are distinct. It also uses a default GregorianCalendar object as its underlying calendar such as for determining leap years. Do not use the result of this method with a calendar other than a default GregorianCalendar.

Note: In general clients should use Calendar.get(ZONE_OFFSET) + Calendar.get(DST_OFFSET) instead of calling this method. @param era The era of the given date. @param year The year in the given date. @param month The month in the given date. Month is 0-based. e.g. 0 for January. @param day The day-in-month of the given date. @param dayOfWeek The day-of-week of the given date. @param millis The milliseconds in day in standard local time. @return The milliseconds to add to UTC to get local time. @exception IllegalArgumentException the era month day dayOfWeek or millis parameters are out of range

Class SimpleTimeZone, int getRawOffset()

Overrides TimeZone Gets the GMT offset for this time zone. @return the GMT offset value in milliseconds @see #setRawOffset
Class SimpleTimeZone, boolean hasSameRules(TimeZone)

ReturnReturns true if this zone has the same rules and offset as another zone. @param other the TimeZone object to be compared with @return true if the given zone is a SimpleTimeZone and has the same rules and offset as this one @since 1.2
Class SimpleTimeZone, int hashCode()

Override hashCode. Generates the hash code for the SimpleDateFormat object. @return the hash code for this object
Class SimpleTimeZone, boolean inDaylightTime(Date)

Overrides TimeZone Queries if the given date is in Daylightdaylight saving time. @return true if daylight saving time is in effective at the given date; Savings Timefalse otherwise.
Class SimpleTimeZone, void setDSTSavings(int)

Sets the amount of time in msmilliseconds that the clock is advanced during DSTdaylight saving time. @param millisSavedDuringDST the number of milliseconds the time is advanced with respect to standard time when the daylight savingssaving time rules are in effect. A positive number typically one hour (3600000). @see #getDSTSavings @since 1.2
Class SimpleTimeZone, void setEndRule(int, int, int)

Sets the DSTdaylight saving time end rule to a fixed date within a month. @param month TheThis month in whichmethod is equivalent thisto: rule
setEndRule(endMonth occursendDay (0-based endTime).
@param dayOfMonthendMonth The datedaylight insaving thattime ending month. Month is a MONTH field value (10-based. e.g. 9 for October). @param timeendDay The timeday of that daythe (numbermonth of millis afteron which the midnight)daylight when DSTsaving time ends. @param endTime The daylight saving ending time in local wall clock time (in milliseconds within the day) which is local daylight time in this case. @exception IllegalArgumentException the month dayOfMonthendMonth endDay or timeendTime parameters are out of range @since 1.2
Class SimpleTimeZone, void setEndRule(int, int, int, int)

Sets the daylight savingssaving endingtime end rule. For example Daylightif Savingsdaylight saving Timetime ends aton the last (-1) Sunday in October at 2 AMam in standardwall clock time. Therefore you can set the end rule by calling: setEndRule(TimeFieldsCalendar.OCTOBER -1 TimeFieldsCalendar.SUNDAY 2*60*60*1000); @param monthendMonth The daylight savingssaving time ending month. Month is a MONTH field value (0-based. ege.g. 09 for JanuaryOctober). @param dayOfWeekInMonthendDay The daylightday savings endingof the day-of-week-in-month. on which the daylight saving time Pleaseends. seeSee the memberclass description for anthe examplespecial cases of this parameter. @param dayOfWeekendDayOfWeek The daylight savingssaving time ending day-of-week. Please seeSee the memberclass description for anthe special examplecases of this parameter. @param timeendTime The daylight savingssaving ending time in local wall clock time (in milliseconds within the day) which is local daylight time in this case. Please see the member description for an example. @exception IllegalArgumentException the monthif dayOfWeekInMonththe dayOfWeekendMonth endDay endDayOfWeek or timeendTime parameters are out of range
Class SimpleTimeZone, void setEndRule(int, int, int, int, boolean)

Sets the DSTdaylight saving time end rule to a weekday before or after a givethe given date within a month e.g. the first Monday on or after the 8th. @param monthendMonth The daylight saving time ending month. in which thisMonth is a ruleMONTH field occursvalue (0-based). @param dayOfMonth A date withine.g. that month9 for (1-basedOctober). @param dayOfWeekendDay The day of the weekmonth on which thisthe ruledaylight saving time occursends. @param timeendDayOfWeek The time ofdaylight that daysaving time (numberending day-of-week. millis@param afterendTime midnight)The when DST endsdaylight saving ending time in local wall clock time (in milliseconds within the day) which is local daylight time in this case. @param after If true this rule selects the first dayOfWeekendDayOfWeek on or after dayOfMonthendDay. If false this rule selects the last dayOfWeekendDayOfWeek on or before dayOfMonthendDay of the month. @exception IllegalArgumentException the month dayOfMonthendMonth endDay endDayOfWeek dayOfWeek or timeendTime parameters are out of range @since 1.2
Class SimpleTimeZone, void setRawOffset(int)

Overrides TimeZone Sets the base time zone offset to GMT. This is the offset to add *to* UTC to get local time. Please @see TimeZone.setRawOffset for descriptions on the parameter.#getRawOffset
Class SimpleTimeZone, void setStartRule(int, int, int)

Sets the DSTdaylight saving time start rule to a fixed date within a month. @param month TheThis month in whichmethod is equivalent thisto: rule
setStartRule(startMonth occursstartDay (0-based startTime).
@param dayOfMonthstartMonth The datedaylight insaving time thatstarting month. Month is a MONTH field value (10-based. e.g. 0 for January). @param timestartDay The timeday of that daythe month (numberon ofwhich the millis afterdaylight saving midnight)time whenstarts. @param startTime The daylight saving DST takes effecttime starting time in local wall clock time which is local standard time in this case. See the class description for the special cases of this parameter. @exception IllegalArgumentException the monthif the dayOfMonthstartMonth startDayOfMonth or timestartTime parameters are out of range @since 1.2
Class SimpleTimeZone, void setStartRule(int, int, int, int)

Sets the daylight savingssaving startingtime start rule. For example Daylightif daylight Savings Timesaving time starts aton the first Sunday in April at 2 AMam in standardlocal time.wall clock Thereforetime you can set the start rule by calling:
setStartRule(TimeFieldsCalendar.APRIL 1 TimeFieldsCalendar.SUNDAY 2*60*60*1000);
@param monthstartMonth The daylight savingssaving time starting month. Month is a MONTH field value (0-based. ege.g. 0 for January). @param dayOfWeekInMonthstartDay The daylightday savings startingof the day-of-week-in-month. on which the daylight saving Pleasetime starts. seeSee the memberclass description for anthe examplespecial cases of this parameter. @param dayOfWeekstartDayOfWeek The daylight savingssaving time starting day-of-week. Please seeSee the memberclass description for anthe examplespecial cases of this parameter. @param timestartTime The daylight savingssaving time starting time in local wall clock time which is local standard time in this case. Please see the member description for an example. @exception IllegalArgumentException the monthif dayOfWeekInMonththe dayOfWeekstartMonth startDay startDayOfWeek or timestartTime parameters are out of range
Class SimpleTimeZone, void setStartRule(int, int, int, int, boolean)

Sets the DSTdaylight saving time start rule to a weekday before or after a givethe given date within a month e.g. the first Monday on or after the 8th. @param monthstartMonth The daylight saving time starting month. in which thisMonth is a ruleMONTH occursfield value (0-based). @param dayOfMonth A date withine.g. that month0 for (1-basedJanuary). @param dayOfWeekstartDay The day of the weekmonth on which thisthe ruledaylight saving time occursstarts. @param timestartDayOfWeek The time ofdaylight that daysaving time (numberstarting day-of-week. millis@param afterstartTime midnight)The daylight when DST takes effectsaving time starting time in local wall clock time which is local standard time in this case. @param after If true this rule selects the first dayOfWeek on or after dayOfMonth. If false this rule selects the last dayOfWeek on or before dayOfMonth. @exception IllegalArgumentException the monthif dayOfMonththe dayOfWeekstartMonth startDay startDayOfWeek or timestartTime parameters are out of range @since 1.2
Class SimpleTimeZone, void setStartYear(int)

Sets the daylight savingssaving time starting year. @param year The daylight savingssaving starting year.
Class SimpleTimeZone, String toString()

ReturnReturns a string representation of this time zone. @return a string representation of this time zone.
Class SimpleTimeZone, boolean useDaylightTime()

Overrides TimeZoneQueries if Queriesthis time zone uses daylight saving time. @return true if this time zone uses Daylightdaylight saving time; Savings Timefalse otherwise.

Class SortedMap

A map that further guarantees that it will be in ascending key order sorted according to the natural ordering of its keys (see the Comparable interface) or by a comparator provided at sorted map creation time. This order is reflected when iterating over the sorted map's collection views (returned by the entrySet keySet and values methods). Several additional operations are provided to take advantage of the ordering. (This interface is the map analogue of the SortedSet interface.)

All keys inserted into a sorted map must implement the Comparable interface (or be accepted by the specified comparator). Furthermore all such keys must be mutually comparable: k1.compareTo(k2) (or comparator.compare(k1 k2)) must not throw a ClassCastException for any elements k1 and k2 in the sorted map. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException.

Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if the sorted map is to correctly implement the Map interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation but a sorted map performs all key comparisons using its compareTo (or compare) method so two keys that are deemed equal by this method are from the standpoint of the sorted map equal. The behavior of a tree map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

All general-purpose sorted map implementation classes should provide four "standard" constructors: 1) A void (no arguments) constructor which creates an empty sorted map sorted according to the natural order of its keys. 2) A constructor with a single argument of type Comparator which creates an empty sorted map sorted according to the specified comparator. 3) A constructor with a single argument of type Map which creates a new map with the same key-value mappings as its argument sorted according to the keys' natural ordering. 4) A constructor with a single argument of type sorted map which creates a new sorted map with the same key-value mappings and the same ordering as the input sorted map. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but the SDK implementation (TreeMap) complies. @author Josh Bloch @version 1.12 0213 12/0203/0001 @see Map @see TreeMap @see SortedSet @see Comparator @see Comparable @see Collection @see ClassCastException @since 1.2


Class SortedSet

A set that further guarantees that its iterator will traverse the set in ascending element order sorted according to the natural ordering of its elements (see Comparable) or by a Comparator provided at sorted set creation time. Several additional operations are provided to take advantage of the ordering. (This interface is the set analogue of SortedMap.)

All elements inserted into an sorted set must implement the Comparable interface (or be accepted by the specified Comparator). Furthermore all such elements must be mutually comparable: e1.compareTo(e2) (or comparator.compare(e1 e2)) must not throw a ClassCastException for any elements e1 and e2 in the sorted set. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException.

Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation but a sorted set performs all element comparisons using its compareTo (or compare) method so two elements that are deemed equal by this method are from the standpoint of the sorted set equal. The behavior of a sorted set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

All general-purpose sorted set implementation classes should provide four "standard" constructors: 1) A void (no arguments) constructor which creates an empty sorted set sorted according to the natural order of its elements. 2) A constructor with a single argument of type Comparator which creates an empty sorted set sorted according to the specified comparator. 3) A constructor with a single argument of type Collection which creates a new sorted set with the same elements as its argument sorted according to the elements' natural ordering. 4) A constructor with a single argument of type SortedSet which creates a new sorted set with the same elements and the same ordering as the input sorted set. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but the SDK implementation (the TreeSet class) complies. @author Josh Bloch @version 1.15 0216 12/0203/0001 @see Set @see TreeSet @see SortedMap @see Collection @see Comparable @see Comparator @see java.lang.ClassCastException @since 1.2


Class Stack

The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided as well as a method to peek at the top item on the stack a method to test for whether the stack is empty and a method to search the stack for an item and discover how far it is from the top.

When a stack is first created it contains no items. @author Jonathan Payne @version 1.24 0225 12/0203/0001 @since JDK1.0


Class StringTokenizer

The string tokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer methods do not distinguish among identifiers numbers and quoted strings nor do they recognize and skip comments.

The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-token basis.

An instance of StringTokenizer behaves in one of two ways depending on whether it was created with the returnDelims flag having the value true or false:

A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed.

A token is returned by taking a substring of the string that was used to create the StringTokenizer object.

The following is one example of the use of the tokenizer. The code:

 StringTokenizer st = new StringTokenizer("this is a test"); while (st.hasMoreTokens()) { println(st.nextToken()); } 

prints the following output:

 this is a test 
@author unascribed @version 1.25 0226 12/0203/0001 @see java.io.StreamTokenizer @since JDK1.0

Class TimeZone

TimeZone represents a time zone offset and also figures out daylight savings.

Typically you get a TimeZone using getDefault which creates a TimeZone based on the time zone where the program is running. For example for a program running in Japan getDefault creates a TimeZone object based on Japanese Standard Time.

You can also get a TimeZone using getTimeZone along with a time zone ID. For instance the time zone ID for the U.S. Pacific Time zone is "America/Los_Angeles". So you can get a U.S. Pacific Time TimeZone object with:

 TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles"); 
You can use the getAvailableIDs method to iterate through all the supported time zone IDs. You can then choose a supported ID to get a TimeZone. If the time zone you want is not represented by one of the supported IDs then youa custom time zone ID can createbe specified to produce a TimeZone. The syntax of a custom time zone ID withis: the
 followingCustomID: syntaxGMT Sign Hours : Minutes GMT Sign Hours Minutes GMT[ Sign Hours Sign: one of +| -]hh[[:]mm] Hours: Digit Digit Digit Minutes: Digit Digit Digit: one of 0 1 2 3 4 5 6 7 8 9 
Hours must be between 0 to 23 and Minutes must be between 00 to 59. For example you might"GMT+10" specifyand "GMT+14:000010" asmean ten hours and ten minutes ahead of GMT respectively.

The format is locale independent and digits must be taken from the Basic Latin block of the Unicode standard. No daylight saving time transition schedule can be specified with a custom time zone ID. TheIf the specified string doesn't match the syntax TimeZone"GMT" that is returnedused. when you specify

When creating a TimeZone the specified custom time zone ID does not include daylight savingsis normalized in the following timesyntax:

 NormalizedCustomID: GMT Sign TwoDigitHours : Minutes Sign: one of + - TwoDigitHours: Digit Digit Minutes: Digit Digit Digit: one of 0 1 2 3 4 5 6 7 8 9 
For example TimeZone.getTimeZone("GMT-8")
.getID() returns "GMT-08:00".

Three-letter time zone IDs

For compatibility with JDK 1.1.x some other three-letter time zone IDs (such as "PST" "CTT" "AST") are also supported. However their use is deprecated because the same abbreviation is often used for multiple time zones (for example "CST" could be U.S. "Central Standard Time" and "China Standard Time") and the Java platform can then only recognize one of them. @see Calendar @see GregorianCalendar @see SimpleTimeZone @version 1.56 0361 12/1803/01 @author Mark Davis David Goldsmith Chen-Lieh Huang Alan Liu @since JDK1.1
Class TimeZone, Object clone()

OverridesCreates Cloneablea copy of this TimeZone. @return a clone of this TimeZone
Class TimeZone, TimeZone getDefault()

Gets the default TimeZone for this host. The source of the default TimeZone may vary with implementation. @return a default TimeZone. @see #setDefault
Class TimeZone, String getDisplayName()

Returns a name of this time zone suitable for presentation to the user in the default locale. This method returns the long name not including daylight savings. If the display name is not available for the locale then this method returns a string in the formatnormalized GMT[+-]hh:mmcustom ID format. @return the human-readable name of this time zone in the default locale. @since 1.2
Class TimeZone, String getDisplayName(Locale)

Returns a name of this time zone suitable for presentation to the user in the specified locale. This method returns the long name not including daylight savings. If the display name is not available for the locale then this method returns a string in the formatnormalized GMT[+-]hh:mmcustom ID format. @param locale the locale in which to supply the display name. @return the human-readable name of this time zone in the given locale or in the default locale if the given locale is not recognized. @since 1.2
Class TimeZone, String getDisplayName(boolean, int)

Returns a name of this time zone suitable for presentation to the user in the default locale. If the display name is not available for the locale then this method returns a string in the formatnormalized GMT[+-]hh:mmcustom ID format. @param daylight if true return the daylight savings name. @param style either LONG or SHORT @return the human-readable name of this time zone in the default locale. @since 1.2
Class TimeZone, String getDisplayName(boolean, int, Locale)

Returns a name of this time zone suitable for presentation to the user in the specified locale. If the display name is not available for the locale then this method returns a string in the formatnormalized GMT[+-]hh:mmcustom ID format. @param daylight if true return the daylight savings name. @param style either LONG or SHORT @param locale the locale in which to supply the display name. @return the human-readable name of this time zone in the given locale or in the default locale if the given locale is not recognized. @exception IllegalArgumentException style is invalid. @since 1.2
Class TimeZone, int getOffset(int, int, int, int, int, int)

Gets the time zone offset for current date modified in case of daylight savings. This is the offset to add *to* UTC to get local time.

This method returns a historically correct offset if an underlying TimeZone implementation subclass supports historical Daylight Saving Time schedule and GMT offset changes. @param era the era of the given date. @param year the year in the given date. @param month the month in the given date. Month is 0-based. e.g. 0 for January. @param day the day-in-month of the given date. @param dayOfWeek the day-of-week of the given date. @param milliseconds the millismilliseconds in day in standard local time. @return the offset in milliseconds to add *to* GMT to get local time. @see Calendar#ZONE_OFFSET @see Calendar#DST_OFFSET

Class TimeZone, int getRawOffset()

Gets unmodified offset NOT modifiedReturns the amount of time in casemilliseconds ofto daylightadd to UTC to savingsget standard time in this time zone. ThisBecause this value is not affected by daylight saving time it is called raw offset.

If an underlying TimeZone implementation subclass supports historical GMT offset changes the method returns the raw offset to addvalue of *to*the UTCcurrent date. In Honolulu for example its raw offset changed from GMT-10:30 to getGMT-10:00 localin time1947 and this method always returns -36000000 milliseconds (i.e. -10 hours). @return the unmodifiedamount of raw offset to addtime in *milliseconds to* UTCadd to getUTC. local@see time.Calendar#ZONE_OFFSET

Class TimeZone, void setDefault(TimeZone)

Sets the TimeZone that is returned by the getDefault method. If zone is null reset the default to the value it had originally when the VM first started. @param zone the new default time zone @see #getDefault
Class TimeZone, void setRawOffset(int)

Sets the base time zone offset to GMT. This is the offset to add *to* UTC to get local time.

If an underlying TimeZone implementation subclass supports historical GMT offset changes the specified GMT offset is set as the latest GMT offset and the difference from the known latest GMT offset value is used to adjust all historical GMT offset values. @param offsetMillis the given base time zone offset to GMT.

Class TimeZone, boolean useDaylightTime()

Queries if this time zone uses daylight savings time.

If an underlying TimeZone implementation subclass supports historical Daylight Saving Time schedule changes the method refers to the latest Daylight Saving Time schedule information. @return true if this time zone uses daylight savings time false otherwise.


Class Timer

A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution or for repeated execution at regular intervals.

Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks sequentially. Timer tasks should complete quickly. If a timer task takes excessive time to complete it "hogs" the timer's task execution thread. This can in turn delay the execution of subsequent tasks which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes.

After the last live reference to a Timer object goes away and all outstanding tasks have completed execution the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However this can take arbitrarily long to occur. By default the task execution thread does not run as a daemon thread so it is capable of keeping an application from terminating. If a caller wants to terminate a timer's task execution thread rapidly the caller should invoke the the timer's cancel method.

If the timer's task execution thread terminates unexpectedly for example because its stop method is invoked any further attempt to schedule a task on the timer will result in an IllegalStateException as if the timer's cancel method had been invoked.

This class is thread-safe: multiple threads can share a single Timer object without the need for external synchronization.

This class does not offer real-time guarantees: it schedules tasks using the Object.wait(long) method.

Implementation note: This class scales to large numbers of concurrently scheduled tasks (thousands should present no problem). Internally it uses a binary heap to represent its task queue so the cost to schedule a task is O(log n) where n is the number of concurrently scheduled tasks. @author Josh Bloch @version 1.7 028 12/0203/0001 @see TimerTask @see Object#wait(long) @since 1.3


Class TimerTask

A task that can be scheduled for one-time or repeated execution by a Timer. @author Josh Bloch @version 1.6 027 12/0203/0001 @see Timer @since 1.3

Class TooManyListenersException

The TooManyListenersException Exception is used as part of the Java Event model to annotate and implement a unicast special case of a multicast Event Source.

The presence of a "throws TooManyListenersException" clause on any given concrete implementation of the normally multicast "void addXyzEventListener" event listener registration pattern is used to annotate that interface as implementing a unicast Listener special case that is that one and only one Listener may be registered on the particular event listener source concurrently.

@see java.util.EventObject @see java.util.EventListener @version 1.10 0011 01/0212/0203 @author Laurence P. G. Cable @since JDK1.1

Class TreeMap

Red-Black tree based implementation of the SortedMap interface. This class guarantees that the map will be in ascending key order sorted according to the natural order for the key's class (see Comparable) or by the comparator provided at creation time depending on which constructor is used.

This implementation provides guaranteed log(n) time cost for the containsKey get put and remove operations. Algorithms are adaptations of those in Cormen Leiserson and Rivest's Introduction to Algorithms.

Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation but a map performs all key comparisons using its compareTo (or compare) method so two keys that are deemed equal by this method are from the standpoint of the sorted map equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

Note that this implementation is not synchronized. If multiple threads access a map concurrently and at least one of the threads modifies the map structurally it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time to prevent accidental unsynchronized access to the map:

 Map m = Collections.synchronizedMap(new TreeMap(...)); 

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map 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 throws 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 and Doug Lea @version 1.43 0254 12/0203/0001 @see Map @see HashMap @see Hashtable @see Comparable @see Comparator @see Collection @see Collections#synchronizedMap(Map) @since 1.2

Class TreeMap, constructor TreeMap(Map)

Constructs a new map containing the same mappings as the given map sorted according to the keys' natural order. All keys inserted into the new map must implement the Comparable interface. Furthermore all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any elements k1 and k2 in the map. This method runs in n*log(n) time. @param m the map whose mappings are to be placed in this map. @throws ClassCastException the keys in t are not Comparable or are not mutually comparable. @throws NullPointerException if the specified map is null.
Class TreeMap, constructor TreeMap(SortedMap)

Constructs a new map containing the same mappings as the given SortedMap sorted according to the same ordering. This method runs in linear time. @param m the sorted map whose mappings are to be placed in this map and whose comparator is to be used to sort this map. @throws NullPointerException if the specified sorted map is null.
Class TreeMap, boolean containsValue(Object)

Returns true if this map maps one or more keys to the specified value. More formally returns true if and only if this map contains at least one mapping to a value v such that (value==null v==null : value.equals(v)). This operation will probably require time linear in the Map size for most implementations of Map. @param value value whose presence in this Map is to be tested. @return true if a mapping to value exists; false otherwise. @since 1.2
Class TreeMap, void putAll(Map)

Copies all of the mappings from the specified map to this map. These mappings replace any mappings that this map had for any of the keys currently in the specified map. @param map mappings to be stored in this map. @throws ClassCastException class of a key or value in the specified map prevents it from being stored in this map. @throws NullPointerException if the given map is null or this map does not permit null keys and a key in the specified keymap is null.
Class TreeMap, Object remove(Object)

Removes the mapping for this key from this TreeMap if present. @param key key for which mapping should be removed @return previous value associated with specified key or null if there was no mapping for key. A null return can also indicate that the map previously associated null with the specified key. @throws ClassCastException key cannot be compared with the keys currently in the map. @throws NullPointerException key is null and this map uses natural order or its comparator does not tolerate null keys.

Class TreeSet

This class implements the Set interface backed by a TreeMap instance. This class guarantees that the sorted set will be in ascending element order sorted according to the natural order of the elements (see Comparable) or by the comparator provided at set creation time depending on which constructor is used.

This implementation provides guaranteed log(n) time cost for the basic operations (add remove and contains).

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation but a TreeSet instance performs all key comparisons using its compareTo (or compare) method so two keys that are deemed equal by this method are from the standpoint of the set equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

Note that this implementation is not synchronized. If multiple threads access a set concurrently and at least one of the threads modifies the set it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time to prevent accidental unsynchronized access to the set:

 SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...)); 

The Iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created in any way except through the iterator's own remove method 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.20 0223 12/0203/0001 @see Collection @see Set @see HashSet @see Comparable @see Comparator @see Collections#synchronizedSortedSet(SortedSet) @see TreeMap @since 1.2

Class TreeSet, constructor TreeSet(Collection)

Constructs a new set containing the elements in the specified collection sorted according to the elements' natural order. All keys inserted into the set must implement the Comparable interface. Furthermore all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any elements k1 and k2 in the set. @param c The elements that will comprise the new set. @throws ClassCastException if the keys in the givenspecified collection are not comparable or are not mutually comparable. @throws NullPointerException if the specified collection is null.
Class TreeSet, constructor TreeSet(Comparator)

Constructs a new empty set sorted according to the givenspecified comparator. All elements inserted into the set must be mutually comparable by the givenspecified comparator: comparator.compare(e1 e2) must not throw a ClassCastException for any elements e1 and e2 in the set. If the user attempts to add an element to the set that violates this constraint the add(Object) call will throw a ClassCastException. @param c the comparator that will be used to sort this set. A null value indicates that the elements' natural ordering should be used.
Class TreeSet, constructor TreeSet(SortedSet)

Constructs a new set containing the same elements as the givenspecified sorted set sorted according to the same ordering. @param s sorted set whose elements will comprise the new set. @throws NullPointerException if the specified sorted set is null.
Class TreeSet, boolean addAll(Collection)

Adds all of the elements in the specified collection to this set. @param c elements to be added @return true if this set changed as a result of the call. @throws ClassCastException if the elements provided cannot be compared with the elements currently in the set. @throws NullPointerException of the specified collection is null.
Class TreeSet, SortedSet headSet(Object)

Returns a view of the portion of this set whose elements are strictly less than toElement. The returned sorted set is backed by this set so changes in the returned sorted set are reflected in this set and vice-versa. The returned sorted set supports all optional set operations.

The sorted set returned by this method will throw an IllegalArgumentException if the user attempts to insert an element greater than or equal to toElement.

Note: this method always returns a view that does not contain its (high) endpoint. If you need a view that does contain this endpoint and the element type allows for calculation of the successor of a givenspecified value merely request a headSet bounded by successor(highEndpoint). For example suppose that s is a sorted set of strings. The following idiom obtains a view containing all of the strings in s that are less than or equal to high:

 SortedSet head = s.headSet(high+"\0");
@param toElement high endpoint (exclusive) of the headSet. @return a view of the portion of this set whose elements are strictly less than toElement. @throws ClassCastException if toElement is not compatible with this set's comparator (or if the set has no comparator if toElement does not implement Comparable). @throws IllegalArgumentException if this set is itself a subSet headSet or tailSet and toElement is not within the specified range of the subSet headSet or tailSet. @throws NullPointerException if toElement is null and this set uses natural ordering or its comparator does not tolerate null elements.
Class TreeSet, boolean remove(Object)

Removes the givenspecified element from this set if it is present. @param o object to be removed from this set if present. @return true if the set contained the specified element. @throws ClassCastException if the specified object cannot be compared with the elements currently in the set.
Class TreeSet, SortedSet subSet(Object, Object)

Returns a view of the portion of this set whose elements range from fromElement inclusive to toElement exclusive. (If fromElement and toElement are equal the returned sorted set is empty.) The returned sorted set is backed by this set so changes in the returned sorted set are reflected in this set and vice-versa. The returned sorted set supports all optional Set operations.

The sorted set returned by this method will throw an IllegalArgumentException if the user attempts to insert an element outside the specified range.

Note: this method always returns a half-open range (which includes its low endpoint but not its high endpoint). If you need a closed range (which includes both endpoints) and the element type allows for calculation of the successor of a givenspecified value merely request the subrange from lowEndpoint to successor(highEndpoint). For example suppose that s is a sorted set of strings. The following idiom obtains a view containing all of the strings in s from low to high inclusive:

 SortedSet sub = s.subSet(low high+"\0"); 
A similar technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the strings in s from low to high exclusive:
 SortedSet sub = s.subSet(low+"\0" high); 
@param fromElement low endpoint (inclusive) of the subSet. @param toElement high endpoint (exclusive) of the subSet. @return a view of the portion of this set whose elements range from fromElement inclusive to toElement exclusive. @throws ClassCastException if fromElement and toElement cannot be compared to one another using this set's comparator (or if the set has no comparator using natural ordering). @throws IllegalArgumentException if fromElement is greater than toElement. @throws NullPointerException if fromElement or toElement is null and this set uses natural order or its comparator does not tolerate null elements.
Class TreeSet, SortedSet tailSet(Object)

Returns a view of the portion of this set whose elements are greater than or equal to fromElement. The returned sorted set is backed by this set so changes in the returned sorted set are reflected in this set and vice-versa. The returned sorted set supports all optional set operations.

The sorted set returned by this method will throw an IllegalArgumentException if the user attempts to insert an element less than fromElement. Note: this method always returns a view that contains its (low) endpoint. If you need a view that does not contain this endpoint and the element type allows for calculation of the successor of a givenspecified value merely request a tailSet bounded by successor(lowEndpoint). For example suppose that s is a sorted set of strings. The following idiom obtains a view containing all of the strings in s that are strictly greater than low:

 SortedSet tail = s.tailSet(low+"\0"); 
@param fromElement low endpoint (inclusive) of the tailSet. @return a view of the portion of this set whose elements are greater than or equal to fromElement. @throws ClassCastException if fromElement is not compatible with this set's comparator (or if the set has no comparator if fromElement does not implement Comparable). @throws IllegalArgumentException if this set is itself a subSet headSet or tailSet and fromElement is not within the specified range of the subSet headSet or tailSet. @throws NullPointerException if fromElement is null and this set uses natural ordering or its comparator does not tolerate null elements.

Class Vector

The Vector class implements a growable array of objects. Like an array it contains components that can be accessed using an integer index. However the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.

Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector the vector's storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.

As of the Java 2 platform v1.2 this class has been retrofitted to implement List so that it becomes a part of Java's collection framework. Unlike the new collection implementations Vector is synchronized.

The Iterators returned by Vector's iterator and listIterator methods are fail-fast: if the Vector 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. The Enumerations returned by Vector's elements method are not fail-fast.

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 Lee Boynton @author Jonathan Payne @version 1.71 0485 12/1803/0001 @see Collection @see List @see ArrayList @see LinkedList @since JDK1.0

Class Vector, constructor Vector(Collection)

Constructs a vector containing the elements of the specified collection in the order they are returned by the collection's iterator. @param c the collection whose elements are to be placed into this vector. @throws NullPointerException if the specified collection is null. @since 1.2
Class Vector, boolean addAll(Collection)

Appends all of the elements in the specified Collection to the end of this Vector 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 Vector and this Vector is nonempty.) @param c elements to be inserted into this Vector. @return true if this Vector changed as a result of the call. @exception ArrayIndexOutOfBoundsException index out of range (index < 0 || index > size()). @throws NullPointerException if the specified collection is null. @since 1.2
Class Vector, boolean addAll(int, Collection)

Inserts all of the elements in in the specified Collection into this Vector 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 Vector 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 Vector. @return true if this Vector changed as a result of the call. @exception ArrayIndexOutOfBoundsException index out of range (index < 0 || index > size()). @throws NullPointerException if the specified collection is null. @since 1.2
Class Vector, int capacity()

Returns the current capacity of this vector. @return the current capacity (the length of its internal data araryarray kept in the field elementData of this vector).
Class Vector, boolean containsAll(Collection)

Returns true if this Vector contains all of the elements in the specified Collection. @param c a collection whose elements will be tested for containment in this Vector @return true if this Vector contains all of the elements in the specified collection. @throws NullPointerException if the specified collection is null.
Class Vector, void copyInto(Object[])

Copies the components of this vector into the specified array. The item at index k in this vector is copied into component k of anArray. The array must be big enough to hold all the objects in this vector else an IndexOutOfBoundsException is thrown. @param anArray the array into which the components get copied. @throws NullPointerException if the given array is null.
Class Vector, Object get(int)

Returns the element at the specified position in this Vector. @param index index of element to return. @return object at the specified index @exception ArrayIndexOutOfBoundsException index is out of range (index < 0 || index >= size()). @since 1.2
Class Vector, Object remove(int)

Removes the element at the specified position in this Vector. shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the Vector. @exception ArrayIndexOutOfBoundsException index out of range (index < 0 || index >= size()). @param index the index of the element to removed. @return element that was removed @since 1.2
Class Vector, boolean removeAll(Collection)

Removes from this Vector all of its elements that are contained in the specified Collection. @param c a collection of elements to be removed from the Vector @return true if this Vector changed as a result of the call. @throws NullPointerException if the specified collection is null. @since 1.2
Class Vector, boolean retainAll(Collection)

Retains only the elements in this Vector that are contained in the specified Collection. In other words removes from this Vector all of its elements that are not contained in the specified Collection. @param c a collection of elements to be retained in this Vector (all other elements are removed) @return true if this Vector changed as a result of the call. @throws NullPointerException if the specified collection is null. @since 1.2
Class Vector, Object set(int, Object)

Replaces the element at the specified position in this Vector with the specified element. @param index index of element to replace. @param element element to be stored at the specified position. @return the element previously at the specified position. @exception ArrayIndexOutOfBoundsException index out of range (index < 0 || index >= size()). @exception IllegalArgumentException fromIndex > toIndex. @since 1.2
Class Vector, Object[] toArray(Object[])

Returns an array containing all of the elements in this Vector in the correct order. The; the runtime type of the returned array is that of the specified array. If the Vector 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 Vector.

If the Vector fits in the specified array with room to spare (i.e. the array has more elements than the Vector) the element in the array immediately following the end of the Vector is set to null. This is useful in determining the length of the Vector only if the caller knows that the Vector does not contain any null elements. @param a the array into which the elements of the Vector 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 Vector. @exception ArrayStoreException the runtime type of a is not a supertype of the runtime type of every element in this Vector. @throws NullPointerException if the given array is null. @since 1.2

Class Vector, void trimToSize()

Trims the capacity of this vector to be the vector's current size. If the capacity of this cectorvector is larger than its current size then the capacity is changed to equal the size by replacing its internal data array kept in the field elementData with a smaller one. An application can use this operation to minimize the storage of a vector.

Class WeakHashMap

A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector that is made finalizable finalized and then reclaimed. When a key has been discarded its entry is effectively removed from the map so this class behaves somewhat differently than other Map implementations.

Both null values and the null key are supported. This class has performance characteristics similar to those of the HashMap class and has the same efficiency parameters of initial capacity and load factor.

Like most collection classes this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap method.

This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated so it is impossible to do a lookup of that key in a WeakHashMap at some later time and be surprised that its entry has been removed. This class will work perfectly well with key objects whose equals methods are not based upon object identity such as String instances. With such recreatable key objects however the automatic removal of WeakHashMap entries whose keys have been discarded may prove to be confusing.

The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods it is possible for the size method to return smaller values over time for the isEmpty method to return false and then true for the containsKey method to return true and later false for a given key for the get method to return a value for a given key but later return null for the put method to return null and the remove method to return false for a key that previously appeared to be in the map and for successive examinations of the key set the value set and the entry set to yield successively smaller numbers of elements.

Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. Therefore a key will automatically be removed only after the weak references to it both inside and outside of the map have been cleared by the garbage collector.

Implementation note: The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys either directly or indirectly since that will prevent the keys from being discarded. Note that a value object may refer indirectly to its key via the WeakHashMap itself; that is a value object may strongly refer to some other key object whose associated value object in turn strongly refers to the key of the first value object. This problem mayOne way to bedeal with this is to wrap values themselves within WeakReferences before inserting as in: m.put(key new WeakReference(value)) and then unwrapping upon each get.

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is fixedcreated 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 releaseiterators 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. @version 1.12 0219 12/0203/0001 @author Doug Lea @author Josh Bloch @author Mark Reinhold @since 1.2 @see java.util.HashMap @see java.lang.ref.WeakReference

Class WeakHashMap, constructor WeakHashMap()

Constructs a new empty WeakHashMap with the default initial capacity (16) and the default load factor which is (0.75).
Class WeakHashMap, constructor WeakHashMap(Map)

Constructs a new WeakHashMap with the same mappings as the specified Map. The WeakHashMap is created with an initial capacity of twice the number ofdefault mappings in the specifiedload factor which is map0.75 or 11and an (whicheverinitial iscapacity greater)sufficient and a default load factor which isto hold the mappings in the specified 0.75Map. @param t the map whose mappings are to be placed in this map. @throws NullPointerException if the specified map is null. @since 1.3
Class WeakHashMap, constructor WeakHashMap(int)

Constructs a new empty WeakHashMap with the given initial capacity and the default load factor which is 0.75. @param initialCapacity The initial capacity of the WeakHashMap @throws IllegalArgumentException If the initial capacity is less than zeronegative.
Class WeakHashMap, constructor WeakHashMap(int, float)

Constructs a new empty WeakHashMap with the given initial capacity and the given load factor. @param initialCapacity The initial capacity of the WeakHashMap @param loadFactor The load factor of the WeakHashMap @throws IllegalArgumentException If the initial capacity is lessnegative than zero or if the load factor is nonpositive.
Class WeakHashMap, boolean containsKey(Object)

Returns true if this map contains a mapping for the specified key. @param key The key whose presence in this map is to be tested @return true if there is a mapping for key; false otherwise
Class WeakHashMap, boolean containsValue(Object)

Returns true if this map maps one or more keys to this value. More formally returns true if and only if this map contains at least one mapping to a value v such that (value==null v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations of map. This implementation iterates over entrySet() searching for an entry with the specified value. 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. @param value value whose presence in this map is to be tested. @return true if this map maps one or more keys to thisthe specified value.
Class WeakHashMap, Set entrySet()

Returns a Setcollection view of the mappings contained in this map. Each element in the returned collection is a Map.Entry. The collection is backed by the map so changes to the map are reflected in the collection and vice-versa. The collection supports element removal which removes the corresponding mapping from the map via the Iterator.remove Collection.remove removeAll retainAll and clear operations. It does not support the add or addAll operations. @return a collection view of the mappings contained in this map. @see Map.Entry
Class WeakHashMap, Object get(Object)

Returns the value to which the specified key is mapped in this weak hash map mapsor null if the specifiedmap contains no mapping for this key. If thisA return mapvalue of null does not containnecessarily aindicate valuethat the map contains no mapping for thisthe key; thenit returnis also possible that the map explicitly maps the key to null. The containsKey method may be used to distinguish these two cases. @param key Thethe key whose associated value if any is to be returned. @return the value to which this map maps the specified key or null if the map contains no mapping for this key. @see #put(Object Object)
Class WeakHashMap, boolean isEmpty()

Returns true if this map contains no key-value mappings. This result is a snapshot and may not reflect unprocessed entries that will be removed before next attempted access because they are no longer referenced.
Class WeakHashMap, Set keySet()

Returns a Setset view of the keys contained in this map. The Setset is backed by the map so changes to the map are reflected in the Setset and vice-versa. (If the map is modified while an iteration over the Set is in progress the results of the iteration are undefined.) The Setset supports element removal which removes the corresponding entrymapping from thethis map via the Iterator.remove Set.remove removeAll retainAll and clear operations. It does not support the add or addAll operations. This implementation returns a Set that subclasses AbstractSet. The subclass's iterator method returns a "wrapper object" over this map's entrySet() iterator. The size method delegates to this map's size method and the contains method delegates to this map's containsKey method. The Set is created the first time this method is called and returned in response to all subsequent calls. No synchronization is performed so there is a slight chance that multiple calls to this method will not all return the same Set. @return a Setset view of the keys contained in this map.
Class WeakHashMap, Object put(Object, Object)

Updates this map so thatAssociates the specified value with the givenspecified key maps to thein giventhis valuemap. If the map previously contained a mapping for key then that mapping is replacedthis andkey the previousold value is returnedreplaced. @param key The key that is to be mapped to the givenwith which the specified value is to be valueassociated. @param value The value to which the givenbe keyassociated is to bewith the specified mappedkey. @return The previous value to which thisassociated with specified key was mapped or null if if there was no mapping for key. A null return can also indicate that the HashMap previously associated null with the specified key.
Class WeakHashMap, void putAll(Map)

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.

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. @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 IllegalArgumentExceptionNullPointerException if some aspect of a key or value in the specified map prevents it from being stored in this map. @throws NullPointerException this map does not permit null keys or values and the specified key or value is null.

Class WeakHashMap, Object remove(Object)

Removes the mapping for the giventhis key from this map if present. @param key The key whose mapping is to be removed from the map. @return Theprevious value toassociated which thiswith specified key was mapped or null if there was no mapping for key. A null return can also indicate that the map previously associated null with the specified key.
Class WeakHashMap, int size()

Returns the number of key-value mappings in this map. Note:This Inresult contrast with most implementations of theis a snapshot and may not Mapreflect interface the time required by this operation is linear in the size of theunprocessed entries that will be removed before next attempted access because they are no maplonger referenced.
Class WeakHashMap, Collection values()

Returns a collection view of the values contained in this map. The collection is backed by the map so changes to the map are reflected in the collection and vice-versa. (If the map is modified while an iteration over the collection is in progress the results of the iteration are undefined.) The collection supports element removal which removes the corresponding entrymapping from thethis map via the Iterator.remove Collection.remove removeAll retainAll and clear operations. It does not support the add or addAll operations. This implementation returns a collection that subclasses abstract collection. The subclass's iterator method returns a "wrapper object" over this map's entrySet() iterator. The size method delegates to this map's size method and the contains method delegates to this map's containsValue method. The collection is created the first time this method is called and returned in response to all subsequent calls. No synchronization is performed so there is a slight chance that multiple calls to this method will not all return the same Collection. @return a collection view of the values contained in this map.