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.11 0916 02/3002/9800 @see Collection @since JDK11.2

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. @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. @see #remove(Object) @see #contains(Object)


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.26 0131 02/2102/9900 @see Collection @see List @see AbstractSequentialList @see AbstractCollection @since JDK11.2

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

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 toKeytoIndex 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.17 0921 02/3002/9800 @see Map @see Collection @since JDK11.2


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.14 0921 02/3002/9800 @see Collection @see List @see AbstractList @see AbstractCollection @since JDK11.2

Class AbstractSequentialList, Object remove(int)

Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).

This implementation first gets a list iterator pointing to the indexed element (with listIterator(index)). Then it removes the element with ListIterator.remove.

Note that this implementation will throw an UnsupportedOperationException if list iterator does not implement the remove operation. @param theindex index of the element to be removed from the List. @return the element that was removed from the list. @throws UnsupportedOperationException if the remove operation is not supported by this list. @throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).


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.8 0914 02/3002/9800 @see Collection @see AbstractCollection @see Set @since JDK11.2

Class AbstractSet, int hashCode()

Returns the hash code value for this set. The hash code of a set is defined to be the sum of the hash codes of the elements in the set. This ensures that s1.equals(s2) implies that s1.hashCode()==s2.hashCode() for any two sets s1 and s2 as required by the general contract of Object.hashCode.

This implementation enumerates over the set calling the hashCode method on each element in the collection and adding up the results. @returnsreturn the hash code value for this set.

Class AbstractSet, boolean removeAll(Collection)

Removes from this collectionset 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 collectionset checking each element returned by the iterator in turn to see if it's is contained in the specified collection. If it's is so contained it's is removed from this collectionset 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 collectionset. @return true if this collectionset changed as a result of the call. @throws UnsupportedOperationException removeAll is not supported by this collectionset. @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. @author Josh Bloch @version 1.19 0425 02/2202/9900 @see Collection @see List @see LinkedList @see Vector @see Collections#synchronizedList(List) @since JDK11.2

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.
Class ArrayList, constructor ArrayList(int)

Constructs an empty list with the specified initial capacity. @param initialCapacity the initial capacity of the list. @exception IllegalArgumentException if the specified initial capacity is negative
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 index index at which to insert first element fromc the specified collection. @param c elements to be inserted into this list. @throws IndexOutOfBoundsException if index out of range (index < 0 || index > size()).
Class ArrayList, boolean contains(Object)

Returns true if this list contains the specified element. @param oelem element whose presence in this List is to be tested.
Class ArrayList, void removeRange(int, int)

Removes from this List all of the elements whose index is between fromIndex inclusive and toIndex exclusive. Shifts any succeeding elements to the left (reduces their index). This call shortens the list by (toIndex - fromIndex) elements. (If toIndex==fromIndex this operation has no effect.) @param fromIndex index of first element to be removed. @param fromIndextoIndex index after last element to be removed.

Class Arrays

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

The documentation for the sorting and searching 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.29 0437 02/2202/9900 @see Comparable @see Comparator @since JDK11.2

Class Arrays, int binarySearch(Object[], Object, Comparator)

Searches the specified array for the specified object using the binary search algorithm. The array must be sorted into ascending order according to the specified comparator (as by the Sort(Object[] Comparator) method above) prior to making this call. If it is not sorted the 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. @param c the comparator by which the array 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 array contains elements that are not mutually comparable using the specified comparator or the search key in not mutually comparable with the elements of the array using this comparator. @see Comparable @see #sort(Object[] Comparator)
Class Arrays, boolean equals(double[], double[])

Returns true if the two specified arrays of doubles 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.

Two doubles d1 and d2 are considered equal if:

 new Double(d1).equals(new Double(d2))
(Unlike the == operator this method considers NaN equals to itself and 0.0d unequal to -0.0d.) @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. @see Double#equals(DoubleObject)
Class Arrays, boolean equals(float[], float[])

Returns true if the two specified arrays of floats 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.

Two doublesfloats d1f1 and d2f2 are considered equal if:

 new DoubleFloat(d1f1).equals(new DoubleFloat(d2f2))
(Unlike the == operator this method considers NaN equals to itself and 0.0d0f unequal to -0.0d0f.) @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. @see DoubleFloat#equals(DoubleObject)
Class Arrays, void fill(Object[], int, int, Object)

Assigns the specified Object reference to each element of the specified range of the specified array of Objects. The range to be filled extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be filled is empty.) @param a the array to be filled. @param fromIndex the index of the first element (inclusive) to be filled with the specified value. @param toIndex the index of the last element (exclusive) to be filled with the specified value. @param val the value to be stored in all elements of the array. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Class Arrays, void fill(boolean[], int, int, boolean)

Assigns the specified boolean value to each element of the specified range of the specified array of booleans. The range to be filled extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be filled is empty.) @param a the array to be filled. @param fromIndex the index of the first element (inclusive) to be filled with the specified value. @param toIndex the index of the last element (exclusive) to be filled with the specified value. @param val the value to be stored in all elements of the array. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Class Arrays, void fill(byte[], int, int, byte)

Assigns the specified byte value to each element of the specified range of the specified array of bytes. The range to be filled extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be filled is empty.) @param a the array to be filled. @param fromIndex the index of the first element (inclusive) to be filled with the specified value. @param toIndex the index of the last element (exclusive) to be filled with the specified value. @param val the value to be stored in all elements of the array. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Class Arrays, void fill(char[], int, int, char)

Assigns the specified char value to each element of the specified range of the specified array of chars. The range to be filled extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be filled is empty.) @param a the array to be filled. @param fromIndex the index of the first element (inclusive) to be filled with the specified value. @param toIndex the index of the last element (exclusive) to be filled with the specified value. @param val the value to be stored in all elements of the array. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Class Arrays, void fill(double[], int, int, double)

Assigns the specified double value to each element of the specified range of the specified array of doubles. The range to be filled extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be filled is empty.) @param a the array to be filled. @param fromIndex the index of the first element (inclusive) to be filled with the specified value. @param toIndex the index of the last element (exclusive) to be filled with the specified value. @param val the value to be stored in all elements of the array. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Class Arrays, void fill(float[], int, int, float)

Assigns the specified float value to each element of the specified range of the specified array of floats. The range to be filled extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be filled is empty.) @param a the array to be filled. @param fromIndex the index of the first element (inclusive) to be filled with the specified value. @param toIndex the index of the last element (exclusive) to be filled with the specified value. @param val the value to be stored in all elements of the array. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Class Arrays, void fill(int[], int, int, int)

Assigns the specified int value to each element of the specified range of the specified array of ints. The range to be filled extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be filled is empty.) @param a the array to be filled. @param fromIndex the index of the first element (inclusive) to be filled with the specified value. @param toIndex the index of the last element (exclusive) to be filled with the specified value. @param val the value to be stored in all elements of the array. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Class Arrays, void fill(long[], int, int, long)

Assigns the specified long value to each element of the specified range of the specified array of longs. The range to be filled extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be filled is empty.) @param a the array to be filled. @param fromIndex the index of the first element (inclusive) to be filled with the specified value. @param toIndex the index of the last element (exclusive) to be filled with the specified value. @param val the value to be stored in all elements of the array. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Class Arrays, void fill(short[], int, int, short)

Assigns the specified short value to each element of the specified range of the specified array of shorts. The range to be filled extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be filled is empty.) @param a the array to be filled. @param fromIndex the index of the first element (inclusive) to be filled with the specified value. @param toIndex the index of the last element (exclusive) to be filled with the specified value. @param val the value to be stored in all elements of the array. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Class Arrays, void sort(Object[], Comparator)

Sorts the specified array of objects according to the order induced by the specified comparator. All elements in the array must be mutually comparable by the specified comparator (that is c.compare(e1 e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance and can approach linear performance on nearly sorted lists. @param a the array to be sorted. @param c the comparator to determine the order of the array. A null value indicates that the elements' natural ordering should be used. @throws ClassCastException if the array contains elements that are not mutually comparable using the specified comparator. @see Comparator

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

Sorts the specified range of the specified array of objects into ascending order according to the natural ordering of its elements. The range to be sorted extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be sorted is empty.) All elements in this range must implement the Comparable interface. Furthermore all elements in this range must be mutually comparable (that is e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance and can approach linear performance on nearly sorted lists. @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 @throws ClassCastException if the array contains elements that are not mutually comparable (for example strings and integers). @see Comparable

Class Arrays, void sort(Object[], int, int, Comparator)

Sorts the specified range of the specified array of objects according to the order induced by the specified comparator. The range to be sorted extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be sorted is empty.) All elements in the range must be mutually comparable by the specified comparator (that is c.compare(e1 e2) must not throw a ClassCastException for any elements e1 and e2 in the range).

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance and can approach linear performance on nearly sorted lists. @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. @param c the comparator to determine the order of the array. A null value indicates that the elements' natural ordering should be used. @throws ClassCastException if the array contains elements that are not mutually comparable using the specified comparator. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length @see Comparator

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

Sorts the specified range of the specified array of bytes 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 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(char[], int, int)

Sorts the specified range of the specified array of chars 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 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(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 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[], 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 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(int[], int, int)

Sorts the specified range of the specified array of ints 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 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(long[], int, int)

Sorts the specified range of the specified array of longs 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 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(short[], int, int)

Sorts the specified range of the specified array of shorts 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 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. @author Arthur van Hoff @author Michael McCloskey @version 1.39 0046 02/1102/2300 @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 sset the BitSet with which to mask this BitSet. @since JDK11.2
Class BitSet, int length()

Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one. Returns zero if the BitSet contains no set bits. @return the logical size of this BitSet. @since JDK11.2

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 JDKplatform 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 GregorianCalendar 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 historial 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. 24:00:00 "belongs" to the following day. That is 23:59 on Dec 31 1969 < 24:00 on Jan 1 1970 < 24:01:00 on Jan 1 1970
  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 the week).

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.4449 01/19/00 @author Mark Davis David Goldsmith Chen-Lieh Huang Alan Liu @since JDK1.1
Class Calendar, int getActualMaximum(int)

Return the maximum value that this field could have given the current date. For example with the date "Feb 3 1997" and the DAY_OF_MONTH field the actual maximum would be 28; for "Feb 3 1996" it s 29. Similarly for a Hebrew calendar for some years the actual maximum for MONTH is 12 and for others 13. The version of this function on Calendar uses an iterative algorithm to determine the actual maximum value for the field. There is almost always a more efficient way to accomplish this (in most cases you can simply return getMaximum()). GregorianCalendar overrides this function with a more efficient implementation. @param field the field to determine the maximum of @return the maximum of the given field for the current date of this Calendar @since 1.2
Class Calendar, int getActualMinimum(int)

Return the minimum value that this field could have given the current date. For the Gregorian calendar this is the same as getMinimum() and getGreatestMinimum(). The version of this function on Calendar uses an iterative algorithm to determine the actual minimum value for the field. There is almost always a more efficient way to accomplish this (in most cases you can simply return getMinimum()). GregorianCalendar overrides this function with a more efficient implementation. @param field the field to determine the minimum of @return the minimum of the given field for the current date of this Calendar @since 1.2
Class Calendar, int hashCode()

Returns a hash code for this calendar. @return a hash code value for this object. @since 1.2
Class Calendar, void roll(int, int)

Time Field Rolling function. Rolls up or down the specified number of units on the given time field. (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. @since 1.2
Class Calendar, int DATE

Field number for get and set indicating the day of the month. This is a synonym for DAY_OF_MONTH. The first day of the month has value 1. @see #DAY_OF_MONTH
Class Calendar, int DAY_OF_MONTH

Field number for get and set indicating the day of the month. This is a synonym for DATE. The first day of the month has value 1. @see #DATE
Class Calendar, int DAY_OF_WEEK

Field number for get and set indicating the day of the week. This field takes values SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY and SATURDAY. @see #SUNDAY @see #MONDAY @see #TUESDAY @see #WEDNESDAY @see #THURSDAY @see #FRIDAY @see #SATURDAY
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. Example: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 15 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 inof a Octobermonth is specified as DAY_OF_WEEK = SundaySUNDAY 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 DAY_OF_YEAR

Field number for get and set indicating the day number within the current year. The first day of the year has value 1.
Class Calendar, int ERA

Field number for get and set indicating the era e.g. AD or BC in the Julian calendar. This is a calendar-specific value; see subclass documentation. @see GregorianCalendar#AD @see GregorianCalendar#BC
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; 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 WEEK_OF_MONTH

Field number for get and set indicating the week number within the current month. The first week of the month as defined by getFirstDayOfWeek() and getMinimalDaysInFirstWeek() has value 1. Subclasses define the value of WEEK_OF_MONTH for days before the first week of the month. @see #getFirstDayOfWeek @see #getMinimalDaysInFirstWeek
Class Calendar, int WEEK_OF_YEAR

Field number for get and set indicating the week number within the current year. The first week of the year as defined by getFirstDayOfWeek() and getMinimalDaysInFirstWeek() has value 1. Subclasses define the value of WEEK_OF_YEAR for days before the first week of the year. @see #getFirstDayOfWeek @see #getMinimalDaysInFirstWeek
Class Calendar, int YEAR

Field number for get and set indicating the year. This is a calendar-specific value; see subclass documentation.

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 JDKSDK 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 JDKSDK comply.

@author Josh Bloch @version 1.25 0931 02/3002/9800 @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 JDK11.2

Class Collection, boolean isEmpty()

Returns true if this collection contains no elements. @returnsreturn true if this collection contains no elements
Class Collection, Iterator iterator()

Returns an iterator over the elements in this collection. There are no guarantees concerning the order in which the elements are returned (unless this collection is an instance of some class that provides a guarantee). @returnsreturn an Iterator over the elements in this collection
Class Collection, Object[] toArray(Object[])

Returns an array containing all of the elements in this collection whose runtime type 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.


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 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.) @author Josh Bloch @version 1.34 0445 02/2217/9900 @see Collection @see Set @see List @see Map @since JDK11.2

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 a "sequential access" list (which provides linear-time positional access).

If the specified list implements the AbstracSequentialList interface this method will do a sequential search instead of a binary search; this offers linear performance instead of n log(n) performance if this method is called on a LinkedList object. @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, Object max(Collection, Comparator)

Returns the maximum element of the given collection according to the order induced by the specified comparator. All elements in the collection must be mutually comparable by the specified comparator (that is comp.compare(e1 e2) must not throw a ClassCastException for any elements e1 and e2 in the collection).

This method iterates over the entire collection hence it requires time proportional to the size of the collection. @param coll the collection whose maximum element is to be determined. @param comp the comparator with which to determine the maximum element. A null value indicates that the elements' natural ordering should be used. @return the maximum element of the given collection according to the specified comparator. @throws ClassCastException if the collection contains elements that are not mutually comparable using the specified comparator. @throws NoSuchElementException if the collection is empty. @see Comparable

Class Collections, Object min(Collection, Comparator)

Returns the minimum element of the given collection according to the order induced by the specified comparator. All elements in the collection must be mutually comparable by the specified comparator (that is comp.compare(e1 e2) must not throw a ClassCastException for any elements e1 and e2 in the collection).

This method iterates over the entire collection hence it requires time proportional to the size of the collection. @param coll the collection whose minimum element is to be determined. @param comp the comparator with which to determine the minimum element. A null value indicates that the elements' natural ordering should be used. @return the minimum element of the given collection according to the specified comparator. @throws ClassCastException if the collection contains elements that are not mutually comparable using the specified comparator. @throws NoSuchElementException if the collection is empty. @see Comparable

Class Collections, void reverse(List)

Reverses the order of the elements in the specified list.

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

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 a "random access" list (which provides near-constant-time positional access). It may require quadratic time for a "sequential access" list. @param list the list to be shuffled. @param rrnd the source of randomness to use to shuffle the list. @throws UnsupportedOperationException if the specified list's list-iterator does not support the set operation.

Class Collections, Set singleton(Object)

Returns an immutable set containing only the specified object. The returned set is serializable. @param o the sole object to be stored in the returned set. @return an immutable set containing only the specified object.
Class Collections, void sort(List, Comparator)

Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is c.compare(e1 e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance and can approach linear performance on nearly sorted lists.

The specified list must be modifiable but need not be resizable. This implementation dumps the specified list into an array sorts the array and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place. @param list the list to be sorted. @param c the comparator to determine the order of the arraylist. A null value indicates that the elements' natural ordering should be used. @throws ClassCastException if the list contains elements that are not mutually comparable using the specified comparator. @throws UnsupportedOperationException if the specified list's list-iterator does not support the set operation. @see Comparator


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 x.compareTo((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.10 0915 02/3002/9800 @see Comparable @see Arrays#sort(Object[] Comparator) @see TreeMap @see TreeSet @see SortedMap @see SortedSet @see java.io.Serializable @since JDK11.2
Class Comparator, int compare(Object, Object)

Compares its two arguments for order. Returns a negative integer zero or a positive integer as the first argument is less than equal to or greater than the second.

The implementor must ensure that sgn(compare(x y)) == -sgn(compare(y x)) for all x and y. (This implies that compare(x y) must throw an exception if and only if compare(y x) throws an exception.)

The implementor must also ensure that the relation is transitive: ((compare(x y)>0) && (compare(y z)>0)) implies compare(x z)>0.

Finally the implementer must ensure that compare(x y)==0 implies that sgn(compare(x z))==sgn(compare(y z)) for all z.

It is generally the case but not strictly required that (compare(x y)==0) == (x.equals(y)). Generally speaking any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals." @param o1 the first object to be compared. @param o2 the second object to be compared. @return a negative integer zero or a positive integer as the first argument is less than equal to or greater than the second. @throws ClassCastException if the arguments' types prevent them from being compared by this Comparator.


Class ConcurrentModificationException

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

For example it is not 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 JDKSDK) 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. @author Josh Bloch @version 1.611 0902/3002/9800 @see Collection @see Iterator @see ListIterator @see Vector @see LinkedList @see HashSet @see Hashtable @see TreeMap @see AbstractList @since JDK11.2

Class ConcurrentModificationException, constructor ConcurrentModificationException(String)

Constructs a ConcurrentModificationException with the specified detail message. @param message the detail message pertaining to this exception.

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.62 0369 01/0821/0001 @see java.text.DateFormat @see java.util.Calendar @see java.util.TimeZone @since JDK1.0

Class Date, int compareTo(Date)

Compares two Dates for ordering. @param anotherDate the Date to be compared. @return the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument. @since JDK11.2
Class Date, int compareTo(Object)

Compares this Date to another Object. If the Object is a Date this function behaves like compareTo(Date). Otherwise it throws a ClassCastException (as Dates are comparable only to other Dates). @param o the Object to be compared. @return the value 0 if the argument is a Date equal to this Date; a value less than 0 if the argument is a Date after this Date; and a value greater than 0 if the argument is a Date before this Date. @exception ClassCastException if the argument is not a Date. @see java.lang.Comparable @since JDK11.2
Class Date, long parse(String)

Attempts to interpret the string s as a representation of a date and time. If the attempt is successful the time indicated is returned represented as the distance measured in milliseconds of that time from the epoch (00:00:00 GMT on January 1 1970). If the attempt fails an IllegalArgumentException is thrown.

It accepts many syntaxes; in particular it recognizes the IETF standard date syntax: "Sat 12 Aug 1995 13:30:00 GMT". It also understands the continental U.S. time-zone abbreviations but for general use a time-zone offset should be used: "Sat 12 Aug 1995 13:30:00 GMT+0430" (4 hours 30 minutes west of the Greenwich meridian). If no time zone is specified the local time zone is assumed. GMT and UTC are considered equivalent.

The string s is processed from left to right looking for data of interest. Any material in s that is within the ASCII parenthesis characters ( and ) is ignored. Parentheses may be nested. Otherwise the only characters permitted within s are these ASCII characters:

 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 +-:/
and whitespace characters.

A consecutive sequence of decimal digits is treated as a decimal number:

A consecutive sequence of letters is regarded as a word and treated as follows:

Once the entire string s has been scanned it is converted to a time result in one of two ways. If a time zone or time-zone offset has been recognized then the year month day of month hour minute and second are interpreted in UTC and then the time-zone offset is applied. Otherwise the year month day of month hour minute and second are interpreted in the local time zone. @param s a string to be parsed as a date. @return the number of milliseconds since January 1 1970 00:00:00 GMT represented by the string argument. @see java.text.DateFormat @deprecated As of JDK version 1.1 replaced by DateFormat.parse(String s).

Class Date, String toLocaleString()

Creates a string representation of this Date object in an implementation-dependent form. The intent is that the form should be familiar to the user of the Java application wherever it may happen to be running. The intent is comparable to that of the "%c" format supported by the strftime() function of ISO C. @return a string representation of this date using the locale conventions. @see java.text.DateFormat @see java.util.Date#toString() @see java.util.Date#toGMTString() @deprecated As of JDK version 1.1 replaced by DateFormat.format(Date date).

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.13 0915 02/2702/9800 @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.15 0317 02/1802/9800 @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.16 0618 02/2902/9800 @since JDK1.0


Class EventListener

A tagging interface that all event listener interfaces must extend. @since JDK1.1

Class EventObject

The Event class is the abstract root class from which all event state objects shall be derived.

All Event'sEvents are constructed with a reference to the object the "source" that is logically deemed to be the object upon which the Event in question initially occurred upon. @since JDK1.1


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 firstearliest weekseven 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 5. 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.4753 @author David Goldsmith Mark Davis Chen-Lieh Huang Alan Liu @since JDK1.1
Class GregorianCalendar, int getActualMaximum(int)

Return the maximum value that this field could have given the current date. For example with the date "Feb 3 1997" and the DAY_OF_MONTH field the actual maximum would be 28; for "Feb 3 1996" it s 29. Similarly for a Hebrew calendar for some years the actual maximum for MONTH is 12 and for others 13. @since 1.2
Class GregorianCalendar, int getActualMinimum(int)

Return the minimum value that this field could have given the current date. For the Gregorian calendar this is the same as getMinimum() and getGreatestMinimum(). @since 1.2
Class GregorianCalendar, void roll(int, int)

Roll a field by a signed amount. @since 1.2

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 intial 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 tethe 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. @author Josh Bloch @author Arthur van Hoff @version 1.2938 0402/2202/9900 @see Object#hashCode() @see Collection @see Map @see TreeMap @see Hashtable @since JDK11.2

Class HashMap, constructor HashMap(Map)

Constructs a new map with the same mappings as the given map. The map is created with a capacity of twice the number of 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.

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 intial 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. @author Josh Bloch @version 1.14 0919 02/3002/9800 @see Collection @see Set @see TreeSet @see Collections#synchronizedSet(Set) @see HashMap @since JDK11.2

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 the specified collection or eleven (whichever is greater) and the default load factor (which is 0.75) is used. @param c the collection whose elements are to be placed into this set.
Class HashSet, boolean contains(Object)

Returns true if this set contains the specified element. @param o element whose presence in this set is to be tested. @return true if this set contains 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 JDK1the 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. @author Arthur van Hoff @author Josh Bloch @version 1.72 0482 02/2202/9900 @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(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 entries 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. @since JDK11.2
Class Hashtable, boolean containsValue(Object)

Returns true if this Hashtable maps one or more keys to this value.

Note that this method is identical in functionality to contains (which predates the Map interface). @param value value whose presence in this Hashtable is to be tested. @return true if this map maps one or more keys to the specified value. @see Map @since JDK11.2

Class Hashtable, Set entrySet()

Returns a Set view of the entries contained in this Hashtable. Each element in this collection is a Map.Entry. The Set is backed by the Hashtable so changes to the Hashtable are reflected in the Set and vice-versa. The Set supports element removal (which removes the corresponding entry from the Hashtable) but not element addition. @return a set view of the mappings contained in this map. @see Map.Entry @since JDK11.2
Class Hashtable, boolean equals(Object)

Compares the specified Object with this Map for equality as per the definition in the Map interface. @return true if the specified Object is equal to this Map. @see Map#equals(Object) @since JDK11.2
Class Hashtable, int hashCode()

Returns the hash code value for this Map as per the definition in the Map interface. @see Map#hashCode() @since JDK11.2
Class Hashtable, Set keySet()

Returns a Set view of the keys contained in this Hashtable. The Set is backed by the Hashtable so changes to the Hashtable are reflected in the Set and vice-versa. The Set supports element removal (which removes the corresponding entry from the Hashtable) but not element addition. @return a set view of the keys contained in this map. @since JDK11.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. @since JDK11.2
Class Hashtable, Collection values()

Returns a Collection view of the values contained in this Hashtable. The Collection is backed by the Hashtable so changes to the Hashtable are reflected in the Collection and vice-versa. The Collection supports element removal (which removes the corresponding entry from the Hashtable) but not element addition. @return a collection view of the values contained in this map. @since JDK11.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.9 0914 02/3002/9800 @see Collection @see ListIterator @see Enumeration @since JDK11.2
Class Iterator, Object next()

Returns the next element in the interation. @returnsreturn the next element in the interationiteration. @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. @author Josh Bloch @version 1.26 0432 02/2202/9900 @see List @see ArrayList @see Vector @see Collections#synchronizedList(List) @since JDK11.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.
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 index index at which to insert first element fromc the specified collection. @param c elements to be inserted into this list. @throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()).
Class LinkedList, void addFirst(Object)

Inserts the given element at the beginning of this list. @param o the element to be inserted at the beginning of this list.
Class LinkedList, void addLast(Object)

Appends the given element to the end of this list. (Identical in function to the add method; included only for consistency.) @param o the element to be inserted at the end of this list.

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. @author Josh Bloch @version 1.15 1032 02/1302/9700 @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 JDK11.2

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. @returnsreturn true if this list contains the specified element.
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 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 this 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 toKeytoIndex 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 ListIterator

An iterator for lists that allows the programmer to traverse the list in either direction and modify the list during iteration. @author Josh Bloch @version 1.11 0916 02/3002/9800 @see Collection @see List @see Iterator @see Enumeration @since JDK11.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 Set. @exception IllegalArgumentException if some aspect of this element prevents it from being added to this Collection.
Class ListIterator, void set(Object)

Replaces the last element returned by next or previous with the specified element (optional operation). This call can be made only if neither ListIterator.remove nor ListIterator.add have been called after the last call to next or previous. @param o the element with which to replace the last element returned by next or previous. @exception UnsupportedOperationException if the set operation is not supported by this list iterator. @exception ClassCastException if the class of the specified element prevents it from being added to this list. @exception IllegalArgumentException if some aspect of the specified element prevents it from being added to this list. @exception IllegalStateException if neither next nor previous have been called or remove or add have been called after the last call to next or previous.

Class ListResourceBundle

ListResourceBundle is a 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 a String key and the second is the value associated with that key. [Right now there's no error-checking code to enforce this so you could specify key-value pairs that have something other than a String as a key. But since the interfaces are defined in terms of String any value with a key that isn't a String will be inaccessible.]

In the following example the keys are of the form "s1"... 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:

 //==================== class MyResource extends ListResourceBundle { public Object[][] getContents() { return contents; } static final Object[][] contents = { // LOCALIZE THIS {"s1" "3"} // starting value in choice field {"s2" "MyDisk"} // starting value in string field {"s3" "3 Mar 96"} // starting value in date field {"s4" "The disk '{1}' contained {0} on {2}."} // initial pattern {"s5" "0"} // first choice number {"s6" "no files"} // first choice value {"s7" "1"} // second choice number {"s8" "one file"} // second choice value {"s9" "2"} // third choice number {"s10" "{0}|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" "Result"} // label for formatted stuff {"s13" "Dialog"} // standard font {"s15" "Pattern"} // label for standard pattern {"s16" new Dimension(1 5)} // real object not just string // END OF MATERIAL TO LOCALIZE }; } //==================== class MyResource_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 disk '{1}' a {0} a {2}."} // initial pattern {"s5" "0"} // first choice number {"s6" "pas de files"} // first choice value {"s7" "1"} // second choice number {"s8" "une file"} // second choice value {"s9" "2"} // third choice number {"s10" "{0}|3 files"} // third choice value {"s11" "Le format a jete une exception: {0}"} // generic exception message {"s12" "ERROR"} // what to show in field in case of error {"s14" "Resulte"} // label for formatted stuff {"s13" "Dialogue"} // standard font {"s15" "Pattern"} // label for standard pattern {"s16" 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 create a Locale object using one of the two constructors in this class:

 Locale(String language String country) Locale(String language String country String variant) 
The first 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 second 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 third argument--the Variant. The Variant codes are vendor and browser-specific. 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 JDKJava 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.21 2955 Jan 199701/19/00 @author Mark Davis @since JDK1.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.
Class Locale, Locale getDefault()

CommonGets method of getting the current default Locale. Usedvalue forof the presentation: menus dialogs etc. Generally setdefault once when your applet or application is initializedlocale for this instance of the Java Virtual thenMachine. never

reset.The (IfJava you do resetVirtual Machine sets the default locale you probably wantduring to reload yourstartup based on GUI so that the changehost isenvironment. reflected in yourIt is used interface.)by Moremany advancedlocale-sensitive programs will allow users to usemethods if no locale is explicitly differentspecified. locales for different fieldsIt can be changed e.g.using inthe asetDefault spreadsheetmethod. Note@return that the initialdefault locale for setting will matchthis instance of the hostJava system.Virtual Machine

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 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, void setDefault(Locale)

Sets the default locale for the whole JVM. Normally set once at thethis beginninginstance of an applicationthe then never resetJava Virtual Machine. setDefaultThis does not resetaffect the host locale.

If there is a security manager its checkPermission method is called with a PropertyPermission("user.language" "write") permission before the default locale is changed.

The Java Virtual Machine sets the default locale during startup based on the host environment. It is used by many locale-sensitive methods if no locale is explicitly specified.

Since changing the default locale may affect many different areas of functionality this method should only be used if the caller is prepared to reinitialize locale-sensitive code running within the same Java Virtual Machine such as the user interface. @throws SecurityException if a security manager exists and its checkPermission method doesn't allow the operation. @throws NullPointerException if newLocale is null @param newLocale Thethe new default Locale.locale @see SecurityManager#checkPermission @see java.util.PropertyPermission


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 JDKSDK comply. @author Josh Bloch @version 1.2732 0902/3002/9800 @see HashMap @see TreeMap @see Hashtable @see SortedMap @see Collection @see Set @since JDK11.2


Class Map.Entry

A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration; more formally the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator except through the iterator's own remove operation or through the setValue operation on a map entry returned by the iterator. @see Map#entrySet() @since 1.2

Class MissingResourceException

Signals that a resource is missing. @see java.iolang.Exception @see ResourceBundle @version 1.912 0901/2119/9800 @author Mark Davis @since JDK1.1

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.16 0318 02/1802/9800 @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 threaads 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.25 0331 02/1802/9800 @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, constructor Observable()

Construct an Observable with zero Observers.
Class Observable, void notifyObservers()

If this object has changed as indicated by the hasChanged method then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed.

Each observer has its update method called with two arguments: this observable object and null. In other words this method is equivalent to:

notifyOvservers notifyObservers(null)
@see java.util.Observable#clearChanged() @see java.util.Observable#hasChanged() @see java.util.Observer#update(java.util.Observable java.lang.Object)

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.14 0616 02/2902/9800 @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.51 9960 02/0402/2200 @since JDK1.0

Class Properties, String getProperty(String)

Searches for the property with the specified key in this property list. If the key is not found in this property list the default property list and its defaults recursively are then checked. The method returns null if the property is not found. @param key the property key. @return the value in this property list with the specified key value. @see java.util.Properties#setProperty @see #defaults
Class Properties, String getProperty(String, String)

Searches for the property with the specified key in this property list. If the key is not found in this property list the default property list and its defaults recursively are then checked. The method returns the default value argument if the property is not found. @param key the hashtable key. @param defaultValue a default value. @return the value in this property list with the specified key value. @see java.util.Properties#setProperty @see #defaults
Class Properties, void load(InputStream)

Reads a property list (key and element pairs) from the input stream. The stream is assumed to be using the ISO 8859-1 character encoding.

Every property occupies one line of the input stream. Each line is terminated by a line terminator (\n or \r or \r\n). Lines from the input stream are processed until end of file is reached on the input stream.

A line that contains only whitespace or whose first non-whitespace character is an ASCII # or is ignored (thus # or indicate comment lines).

Every line other than a blank line or a comment line describes one property to be added to the table (except that if a line ends with \ then the following line if it exists is treated as a continuation line as described below). The key consists of all the characters in the line starting with the first non-whitespace character and up to but not including the first ASCII = : or whitespace character. All of the key termination characters may be included in the key by preceding them with a \. Any whitespace after the key is skipped; if the first non-whitespace character after the key is = or : then it is ignored and any whitespace characters after it are also skipped. All remaining characters on the line become part of the associated element string. Within the element string the ASCII escape sequences \t \n \r \\ \" \' \ (a backslash and a space) and \\\uxxxx are recognized and converted to single characters. Moreover if the last character on the line is \ then the next line is treated as a continuation of the current line; the \ and line terminator are simply discarded and any leading whitespace characters on the continuation line are also discarded and are not part of the element string.

As an example each of the following four lines specifies the key "Truth" and the associated element value "Beauty":

 Truth = Beauty Truth:Beauty Truth :Beauty 
As another example the following three lines specify a single property:

 fruits apple banana pear \ cantaloupe watermelon \ kiwi mango 
The key is "fruits" and the associated element is:

"apple banana pear cantaloupe watermelon kiwi mango"
Note that a space appears before each \ so that a space will appear after each comma in the final result; the \ line terminator and leading whitespace on the continuation line are merely discarded and are not replaced by one or more other characters.

As a third example the line:

cheeses 
specifies that the key is "cheeses" and the associated element is the empty string.

@param ininStream the input stream. @exception IOException if an error occurred when reading from the input stream.

Class Properties, void save(OutputStream, String)

Calls the store(OutputStream out String header) method and suppresses IOExceptions that were thrown. @deprecated This method does not throw an IOException if an I/O error occurs while saving the property list. As of JDKthe Java 2 platform 1v1.2 the preferred way to save a properties list is via the store(OutputStream out String header) method. @param out an output stream. @param header a description of the property list. @exception ClassCastException if this Properties object contains any keys or values that are not Strings.
Class Properties, Object setProperty(String, String)

Calls the hashtable method put. Provided for parallelism with the getPropertiesgetProperty method. Enforces use of strings for property keys and values. @param key the key to be placed into this property list. @param value the value corresponding to key. @see #getProperty @since JDK11.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. SpaceLeading 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.


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.17 9924 00/0402/2202 @author Roland Schemers @since 1.2 @serial exclude


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 generalparticular 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 you pass to ResourceBundle.getBundle() is the file name of the properties file not the class name of the object that is returned.

For example if you say ResourceBundle.getBundle("MyResources" new Locale("fr" "FR")); the resource bundle lookup mechanism will search the class path for a file called MyResources_fr_FR.properties.

If a real class and a properties file with a particular name both exist the class wins; the properties file will only be used if there is no class with the desired name.

In the following example the keys are of the form "s1"... 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 s4=Der disk '{1}' a {0} a {2}. s5=0 s6=keine Datein s7=1 s8=ein Datei s9=2 s10={0}|3 Datein s11=Der Format worf ein Exception: {0} s12=ERROR s14=Resulte s13=Dialogue s15=Pattern s16=1 3 
@see ResourceBundle @see ListResourceBundle @see Properties @since JDK1.1

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.27 0434 02/2202/9900 @see java.lang.Math#random() @since JDK1.0

Class Random, boolean nextBoolean()

Returns the next pseudorandom uniformly distributed boolean value from this random number generator's sequence. The general contract of nextBoolean is that one boolean value is pseudorandomly generated and returned. The values true and false are produced with (approximately) equal probability. The method nextBoolean is implemented by class Random as follows:
 public boolean nextBoolean() {return next(1) = 0;} 
@return the next pseudorandom uniformly distributed boolean value from this random number generator's sequence. @since JDK11.2
Class Random, double nextGaussian()

Returns the next pseudorandom Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.

The general contract of nextGaussian is that one double value chosen from (approximately) the usual normal distribution with mean 0.0 and standard deviation 1.0 is pseudorandomly generated and returned. The method nextGaussian is implemented by class Random as follows:

 synchronized public double nextGaussian() { if (haveNextNextGaussian) { haveNextNextGaussian = false; return nextNextGaussian; } else { double v1 v2 s; do { v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0 v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0 s = v1 * v1 + v2 * v2; } while (s >= 1 || s == 0); double multiplier = Math.sqrt(-2 * Math.log(s)/s); nextNextGaussian = v2 * multiplier; haveNextNextGaussian = true; return v1 * multiplier; } }
This uses the polar method of G. E. P. Box M. E. Muller and G. Marsaglia as described by Donald E. Knuth in The Art of Computer Programming Volume 2: Seminumerical Algorithms section 3.4.1 subsection C algorithm P. Note that it generates two independent values at the cost of only one call to Math.log and one call to Math.sqrt. @return the next pseudorandom Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.
Class Random, int nextInt(int)

Returns a pseudorandom uniformly distributed int value between 0 (inclusive) and the specified value (exclusive) drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All n possible int values are produced with (approximately) equal probability. The method nextInt(int n) is implemented by class Random as follows:
 public int nextInt(int n) { if (n<0) throw new IllegalArgumentException("n must be positive"); if ((n & -n) == n) // i.e. n is a power of 2 return (int)((n * (long)next(31)) >> 31); int bits val; do { bits = next(31); val = bits % n; } while(bits - val + (n-1) <0); return val; } 

The hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits then the algorithm shown would choose int values from the stated range with perfect uniformity.

The algorithm is slightly tricky. It rejects values that would result in an uneven distribution (due to the fact that 2^31 is not divisible by n). The probability of a value being rejected depends on n. The worst case is n=2^30+1 for which the probability of a reject is 1/2 and the expected number of iterations before the loop terminates is 2.

The algorithm treats the case where n is a power of two specially: it returns the correct number of high-order bits from the underlying pseudo-random number generator. In the absence of special treatment the correct number of low-order bits would be returned. Linear congruential pseudo-random number generators such as the one implemented by this class are known to have short periods in the sequence of values of their low-order bits. Thus this special case greatly increases the length of the sequence of values returned by successive calls to this method if n is a small power of two. @parameterparam n the bound on the random number to be returned. Must be positive. @return a pseudorandom uniformly distributed int value between 0 (inclusive) and n (exclusive). @exception IllegalArgumentException n is not positive. @since JDK11.2


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 classes that inherit from ResourceBundle. Each related subclass of ResourceBundle has the same base name plus an additional component that identifies its locale. For example suppose your resource bundle is named MyResources. The first class you are likely to write is the default resource bundle which simply has the same name as its family--MyResources. You can also provide as many related locale-specific classes as you need: for example perhaps you would provide a German one named MyResources_de.

Each related subclass of ResourceBundle contains the same items but the items have been translated for the locale represented by that ResourceBundle subclass. For example both MyResources and MyResources_de may have a String that's used on a button for confirmingcanceling operations. In MyResources the String may contain OKCancel and in MyResources_de it may contain GutAbbrechen.

If there are different resources for different countries you can make specializations: for example MyResources_de_CH is 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 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 propertyproperties 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:

 class MyResource 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(myResourceBundle.getString("OkKey")); button2 = new Button(myResourceBundle.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 number of other methods for getting different types of objects such as getStringArray. If you don't have an object that matches one of these methods you can use getObject and 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 JDKJava 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 Kingdom 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) abstract 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) { if (key.equals("okKey")) return "Gut"; if (key.equals("cancelKey")) return "Vernichten"; return null; } } // English language default (must provide even though all the data is // in the root locale) public class MyResources_en extends MyResources { public Object handleGetObject(String key) { return null; } } // English language United Kingdom (Great Britain) public class MyResources_en_GB extends MyResources { public Object handleGetObject(String key) { // don't need okKey since parent level handles it. if (key.equals("cancelKey")) return "DisposeAbbrechen"; 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, Locale, ClassLoader)

Get the appropriate ResourceBundle subclass. @param baseName see class description. @param locale see class description. @param loader the ClassLoader to load the resource from.
Class ResourceBundle, Object getObject(String)

Get an object from a ResourceBundle. @param key see class description. @exception NullPointerException if key is null.
Class ResourceBundle, String getString(String)

Get an object from a ResourceBundle.
Convenience method to save casting. @param key see class description. @exception NullPointerException if key is null.
Class ResourceBundle, String[] getStringArray(String)

Get an object from a ResourceBundle.
Convenience method to save casting. @param key see class description. @exception NullPointerException if key is null.
Class ResourceBundle, Object handleGetObject(String)

Get an object from a ResourceBundle. NOTE: Subclasses must override. @param key see class description. @exception NullPointerException if key is null.

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. @author Josh Bloch @version 1.18 0923 02/3002/9800 @see Collection @see List @see SortedSet @see HashSet @see TreeSet @see AbstractSet @see Collections#singleton(java.lang.Object) @see Collections#EMPTY_SET @since JDK11.2

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.

Class SimpleTimeZone

SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone for use with a Gregorian calendar. This class does not handle historical changes.

Use a negative value for dayOfWeekInMonth to indicate that SimpleTimeZone should count from the end of the month backwards. For example Daylight Savings Time ends at the last (dayOfWeekInMonth = -1) Sunday in October at 2 AM in standard time. @see Calendar @see GregorianCalendar @see TimeZone @version 1.32 0338 01/0819/00 @author David Goldsmith Mark Davis Chen-Lieh Huang Alan Liu

Class SimpleTimeZone, constructor SimpleTimeZone(int, String, int, int, int, int, int, int, int, int)

Construct a SimpleTimeZone with the given base time zone offset from GMT time zone ID time to start and end the daylight time. Timezone IDs can be obtained from TimeZone.getAvailableIDs. Normally you should use TimeZone.getDefault 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 constructor specifies day-of-week-in-month rules. That is if the startDay is 1 and the startDayOfWeek is SUNDAY then this indicates the first Sunday in the startMonth. A startDay of -1 likewise indicates the last Sunday. However by using negative or zero values for certain parameters other types of rules can be specified. Day of month. To specify an exact day of the month such as March 1 set startDayOfWeek to zero. Day of week after day of month. To specify the first day of the week occurring on or after an exact day of the month make the day of the week negative. For example if startDay is 5 and startDayOfWeek is -MONDAY this indicates the first Monday on or after the 5th day of the 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 the startMonth. The above examples refer to the startMonth startDay and startDayOfWeek; the same applies for the endMonth endDay and endDayOfWeek. @param rawOffset The given base time zone offset to GMT. @param ID The time zone ID which is obtained from TimeZone.getAvailableIDs. @param startMonth The daylight savings starting month. Month is 0-based. eg 0 for January. @param startDay The daylight savings starting day-of-week-in-month. Please see the member description for an example. @param startDayOfWeek The daylight savings starting day-of-week. Please see the member description for an example. @param startTime The daylight savings starting time in local wall time which is standard time in this case. Please see the member description for an example. @param endMonth The daylight savings ending month. Month is 0-based. eg 0 for January. @param endDay The daylight savings ending day-of-week-in-month. Please see the member description for an example. @param endDayOfWeek The daylight savings ending day-of-week. Please see the member description for an example. @param endTime The daylight savings ending time in local wall time which is daylight time in this case. Please see the member description for an example. @exception IllegalArgumentException 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)

Constructor. This constructor is identical to the 10-argument constructor but also takes a dstSavings parameter. @param dstSavings The amount of time in ms saved during DST. @exception IllegalArgumentException the month day dayOfWeek or time parameters are out of range for the start or end rule @since 1.2
Class SimpleTimeZone, int getDSTSavings()

Returns the amount of time in ms that the clock is advanced during DST. @return the number of milliseconds the time is advanced with respect to standard time when the daylight savings rules are in effect. A positive number typically one hour (3600000). @since 1.2
Class SimpleTimeZone, int getOffset(int, int, int, int, int, int)

OverridesReturns TimeZone Gets offset for current datethe modifieddifference in case of daylight savings. This is themilliseconds offset to addbetween local time *to*and UTC to gettaking localinto time.account Getsboth the time zoneraw offset for current date modifiedand in casethe effect of daylight savings. This isfor the offset to add *to* UTC tospecified get localdate and time. AssumeThis method assumes that the start and end month are distinct. This methodIt may return incorrect resultsalso uses a default forGregorianCalendar rules that start at the end of Februaryobject as its underlying calendar such as for (e.g.determining lastleap Sundayyears. inDo February)not oruse the beginningresult of Marchthis (e.g.method Marchwith 1)a calendar other than a default GregorianCalendar. To

Note: avoid such inaccuraciesIn 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 offsetmilliseconds to add *to* GMTUTC to get local time. @exception IllegalArgumentException the era month day dayOfWeek or millis parameters are out of range

Class SimpleTimeZone, boolean hasSameRules(TimeZone)

Return 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 has the same rules and offset as this one @since 1.2
Class SimpleTimeZone, void setDSTSavings(int)

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

Sets the DST end rule to a fixed date within a month. @param month The month in which this rule occurs (0-based). @param dayOfMonth The date in that month (1-based). @param time The time of that day (number of millis after midnight) when DST ends in local wall time which is daylight time in this case. @exception IllegalArgumentException the month dayOfMonth or time parameters are out of range @since 1.2
Class SimpleTimeZone, void setEndRule(int, int, int, int, boolean)

Sets the DST end rule to a weekday before or after a give date within a month e.g. the first Monday on or after the 8th. @param month The month in which this rule occurs (0-based). @param dayOfMonth A date within that month (1-based). @param dayOfWeek The day of the week on which this rule occurs. @param time The time of that day (number of millis after midnight) when DST ends in local wall time which is daylight 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 month dayOfMonth dayOfWeek or time parameters are out of range @since 1.2
Class SimpleTimeZone, void setStartRule(int, int, int)

Sets the DST start rule to a fixed date within a month. @param month The month in which this rule occurs (0-based). @param dayOfMonth The date in that month (1-based). @param time The time of that day (number of millis after midnight) when DST takes effect in local wall time which is standard time in this case. @exception IllegalArgumentException the month dayOfMonth or time parameters are out of range @since 1.2
Class SimpleTimeZone, void setStartRule(int, int, int, int, boolean)

Sets the DST start rule to a weekday before or after a give date within a month e.g. the first Monday on or after the 8th. @param month The month in which this rule occurs (0-based). @param dayOfMonth A date within that month (1-based). @param dayOfWeek The day of the week on which this rule occurs. @param time The time of that day (number of millis after midnight) when DST takes effect in local wall time which is 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 month dayOfMonth dayOfWeek or time parameters are out of range @since 1.2

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 JDKSDK implementation (TreeMap) complies. @author Josh Bloch @version 1.712 0902/3002/9800 @see Map @see TreeMap @see SortedSet @see Comparator @see Comparable @see Collection @see ClassCastException @since JDK11.2

Class SortedMap, SortedMap headMap(Object)

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

The map returned by this method will throw an IllegalArgumentException if the user attempts to insert a key outside the specified range.

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 key type allows for calculation of the successor a given key merely request a headMap bounded by successor(highEndpoint). For example suppose that suppose that m is a map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are less than or equal to high:

 Map head = m.headMap(high+"\0");
@param toKey high endpoint (exclusive) of the subMap. @return a view of the specified initial range of this sorted map. @throws ClassCastException if toKey cannot be comparedis not compatible with thethis keysmap's currentlycomparator in(or the sortedif the map has no comparator if toKey does not implement Comparable). (Implementations may but are not required to throw this exception underif toKey cannot be compared to keys currently in the map. @throws IllegalArgumentException if this map is itself a subMap headMap or tailMap theseand toKey is not within the specified circumstancesrange of the subMap headMap or tailMap.) @throws NullPointerException if toKey is null and this sorted map does not tolerate null keys.
Class SortedMap, SortedMap subMap(Object, Object)

Returns a view of the portion of this sorted map whose keys range from fromKey inclusive to toKey exclusive. (If fromKey and toKey are equal the returned sorted map is empty.) The returned sorted map is backed by this sorted map so changes in the returned sorted map are reflected in this sorted map and vice-versa. The returned Map supports all optional map operations that this sorted map supports.

The map returned by this method will throw an IllegalArgumentException if the user attempts to insert a key 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 key type allows for calculation of the successor a given key merely request the subrange from lowEndpoint to successor(highEndpoint). For example suppose that m is a map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high inclusive:

 Map sub = m.subMap(low high+"\0");
A similarly technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high exclusive:
 Map sub = m.subMap(low+"\0" high);
@param fromKey low endpoint (inclusive) of the subMap. @param toKey high endpoint (exclusive) of the subMap. @return a view of the specified range within this sorted map. @throws ClassCastException if fromKey orand toKey cannot be compared withto the keys currently inone another using this themap's sortedcomparator (or if the map has no comparator using natural ordering). (Implementations may but are not required to throw this exception underif fromKey or toKey cannot be compared to keys currently in these circumstancesthe map.) @throws NullPointerExceptionIllegalArgumentException if fromKey oris greater than toKey; or if this map is nullitself and this sorted map does nota subMap headMap or tailMap and toleratefromKey or nulltoKey keysare not within the specified range of the subMap headMap or tailMap. @throws IllegalArgumentExceptionNullPointerException if fromKey or toKey is greaternull thanand this sorted map does not tolerate toKeynull keys.
Class SortedMap, SortedMap tailMap(Object)

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

The map returned by this method will throw an IllegalArgumentException if the user attempts to insert a key outside the specified range.

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 a given value merely request a tailMap bounded by successor(lowEndpoint). For example suppose that suppose that m is a map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are strictly greater than low:

 Map tail = m.tailMap(low+"\0");
@param fromKey low endpoint (inclusive) of the tailMap. @return a view of the specified final range of this sorted map. @throws ClassCastException if fromKey cannot be comparedis not compatible with thethis keysmap's currentlycomparator in(or the sortedif the map has no comparator if fromKey does not implement Comparable). (Implementations may but are not required to throw this exception underif fromKey cannot be compared to keys currently in these circumstancesthe map.) @throws IllegalArgumentException if this map is itself a subMap headMap or tailMap and fromKey is not within the specified range of the subMap headMap or tailMap. @throws NullPointerException if fromKey is null and this sorted map does not tolerate null keys.

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 JDKSDK implementation (the TreeSet class) complies. @author Josh Bloch @version 1.1015 0402/2202/9900 @see Set @see TreeSet @see SortedMap @see Collection @see Comparable @see Comparator @see java.lang.ClassCastException @since JDK11.2

Class SortedSet, SortedSet headSet(Object)

Returns a view of the portion of this sorted set whose elements are strictly less than toElement. The returned sorted set is backed by this sorted set so changes in the returned sorted set are reflected in this sorted 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 a element outside the specified range.

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 a given 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 specified initial range of this sorted set. @throws ClassCastException if toElement cannot be comparedis not compatible with thethis elementsset's currentlycomparator in(or the sortedif the set has no comparator if toElement does not implement Comparable). (Implementations may but are not required to throw this exception underif toElement cannot be compared to elements currently in these circumstancesthe set.) @throws NullPointerException if toElement is null and this sorted set does not tolerate null elements. @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.
Class SortedSet, SortedSet subSet(Object, Object)

Returns a view of the portion of this sorted 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 sorted set so changes in the returned sorted set are reflected in this sorted set and vice-versa. The returned sorted set supports all optional set operations that this sorted set supports.

The sorted set returned by this method will throw an IllegalArgumentException if the user attempts to insert a 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 a given 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 specified range within this sorted set. @throws ClassCastException if fromElement orand toElement cannot be compared withto the elements currently inone another using this theset's sortedcomparator (or if the set has no comparator using natural ordering). (Implementations may but are not required to throw this exception underif fromElement or toElement cannot be compared to elements currently in these circumstancesthe set.) @throws NullPointerExceptionIllegalArgumentException if fromElement oris greater than toElement; or if this set is nullitself and this sorted set does nota subSet headSet or tailSet and toleratefromElement or nulltoElement elementsare not within the specified range of the subSet headSet or tailSet. @throws IllegalArgumentExceptionNullPointerException if fromElement or toElement is greaternull thanand this sorted set does not tolerate toElementnull elements.
Class SortedSet, SortedSet tailSet(Object)

Returns a view of the portion of this sorted set whose elements are greater than or equal to fromElement. The returned sorted set is backed by this sorted set so changes in the returned sorted set are reflected in this sorted 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 a element outside the specified range.

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 a given 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 specified final range of this sorted set. @throws ClassCastException if fromElement cannot be comparedis not compatible with thethis elementsset's currentlycomparator in(or the sortedif the set has no comparator if fromElement does not implement Comparable). (Implementations may but are not required to throw this exception underif fromElement cannot be compared to elements currently in these circumstancesthe set.) @throws NullPointerException if fromElement is null and this sorted set does not tolerate null elements. @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.

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.22 0924 02/2702/9800 @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 returnTokensreturnDelims 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.1925 0302/1802/9800 @see java.io.StreamTokenizer @since JDK1.0
Class StringTokenizer, constructor StringTokenizer(String)

Constructs a string tokenizer for the specified string. The tokenizer uses the default delimiter set which is "&nbsp;&#92;t\n\r\f": the space character the tab character the newline character the carriage-return character and the form-feed character. Delimiter characters themselves will not be treated as tokens. @param str a string to be parsed.
Class StringTokenizer, constructor StringTokenizer(String, String, boolean)

Constructs a string tokenizer for the specified string. All characters in the delim argument are the delimiters for separating tokens.

If the returnTokensreturnDelims flag is true then the delimiter characters are also returned as tokens. Each delimiter is returned as a string of length one. If the flag is false the delimiter characters are skipped and only serve as separators between tokens. @param str a string to be parsed. @param delim the delimiters. @param returnTokensreturnDelims flag indicating whether to return the delimiters as tokens.


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 PacificU.S. StandardPacific Time zone is "PSTAmerica/Los_Angeles". So you can get a PSTU.S. Pacific Time TimeZone object with:

 TimeZone tz = TimeZone.getTimeZone("PSTAmerica/Los_Angeles"); 
You can use 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 you can create a custom time zone ID with the following syntax:
 GMT[+|-]hh[[:]mm] 
For example you might specify GMT+14:00 as a custom time zone ID. The TimeZone that is returned when you specify a custom time zone ID does not include daylight savings time.

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.39 0952 07/2706/00 @author Mark Davis David Goldsmith Chen-Lieh Huang Alan Liu @since JDK1.1

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 format GMT[+-]hh:mm. @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 format GMT[+-]hh:mm. @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 format GMT[+-]hh:mm. @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 format GMT[+-]hh:mm. @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, TimeZone getTimeZone(String)

Gets the TimeZone for the given ID. @param ID the ID for a TimeZone either an abbreviation such as "PST" a full name such as "America/Los_Angeles" or a custom ID such as "GMT-8:00". Note that the support of abbreviations is for JDK 1.1.x compatibility only and full names should be used. @return the specified TimeZone or the GMT zone if the given ID cannot be understood.
Class TimeZone, boolean hasSameRules(TimeZone)

Returns true if this zone has the same rule and offset as another zone. That is if this zone differs only in ID if at all. Returns false if the other zone is null. @param other the TimeZone object to be compared with @return true if the givenother zone is not null and is the same as this one with the possible exception of the ID @since 1.2
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
Class TimeZone, int LONG

A style specifier for getDisplayName() indicating a long name such as "Pacific Standard Time." @see #SHORT @since 1.2
Class TimeZone, int SHORT

A style specifier for getDisplayName() indicating a short name such as "PST." @see #LONG @since 1.2

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.7 9810 00/0902/2102 @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 CormanCormen 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. @author Josh Bloch and Doug Lea @version 1.3343 0402/2202/9900 @see Map @see HashMap @see Hashtable @see Comparable @see Comparator @see Collection @see Collections#synchronizedMap(Map) @since JDK11.2

Class TreeMap, constructor TreeMap(Comparator)

Constructs a new empty map sorted according to the given comparator. All keys inserted into the map must be mutually comparable by the given comparator: comparator.compare(k1 k2) must not throw a ClassCastException for any keys k1 and k2 in the map. If the user attempts to put a key into the map that violates this constraint the put(Object key Object value) call will throw a ClassCastException. @param c the comparator that will be used to sort this map. A null value indicates that the keys' natural ordering should be used.
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.
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.
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. @since JDK11.2
Class TreeMap, SortedMap headMap(Object)

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

The sorted map returned by this method will throw an IllegalArgumentException if the user attempts to insert a key greater than or equal to toKey.

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 key type allows for calculation of the successor a given key merely request a headMap bounded by successor(highEndpoint). For example suppose that suppose that m is a sorted map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are less than or equal to high:

 SortedMap head = m.headMap(high+"\0"); 
@param toKey high endpoint (exclusive) of the headMap. @return a view of the portion of this map whose keys are strictly less than toKey. @throws ClassCastException if toKey is not compatible with this map's comparator (or if the map has no comparator if toKey does not implement Comparable). @throws IllegalArgumentException if this map is itself a subMap headMap or tailMap and toKey is not within the specified range of the subMap headMap or tailMap. @throws NullPointerException if toKey is null and this map uses natural order or its comparator does * not tolerate null keys.
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 t Mappingsmap 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 this map does not permit null keys and a specified key is null.
Class TreeMap, SortedMap subMap(Object, Object)

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

The sorted map returned by this method will throw an IllegalArgumentException if the user attempts to insert a key less than fromKey or greater than or equal to toKey.

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 key type allows for calculation of the successor a given key merely request the subrange from lowEndpoint to successor(highEndpoint). For example suppose that m is a sorted map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high inclusive:

 SortedMap sub = m.submap(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 key-value mappings in m whose keys are between low and high exclusive:
 SortedMap sub = m.subMap(low+"\0" high);
@param fromKey low endpoint (inclusive) of the subMap. @param toKey high endpoint (exclusive) of the subMap. @return a view of the portion of this map whose keys range from fromKey inclusive to toKey exclusive. @throws NullPointerExceptionClassCastException if fromKey orand toKey iscannot nullbe andcompared to one another using this map's usescomparator natural(or order or its comparator does not tolerateif the map has no comparator using nullnatural keysordering). @throws IllegalArgumentException if fromKey is greater than toKey. @throws NullPointerException if fromKey or toKey is null and this map uses natural order or its comparator does not tolerate null keys.
Class TreeMap, SortedMap tailMap(Object)

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

The sorted map returned by this method will throw an IllegalArgumentException if the user attempts to insert a key less than fromKey.

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 a given value merely request a tailMap bounded by successor(lowEndpoint). For For example suppose that suppose that m is a sorted map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are strictly greater than low:

 SortedMap tail = m.tailMap(low+"\0"); 
@param fromKey low endpoint (inclusive) of the tailMap. @return a view of the portion of this map whose keys are greater than or equal to fromKey. @throws ClassCastException if fromKey is not compatible with this map's comparator (or if the map has no comparator if fromKey does not implement Comparable). @throws IllegalArgumentException if this map is itself a subMap headMap or tailMap and fromKey is not within the specified range of the subMap headMap or tailMap. @throws NullPointerException if fromKey is null and this map uses natural orderingorder 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. @author Josh Bloch @version 1.13 0920 02/3002/9800 @see Collection @see Set @see HashSet @see Comparable @see Comparator @see Collections#synchronizedSortedSet(SortedSet) @see TreeMap @since JDK11.2

Class TreeSet, constructor TreeSet(Comparator)

Constructs a new empty set sorted according to the given comparator. All elements inserted into the set must be mutually comparable by the given 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, Comparator comparator()

Returns the comparator used to order this sorted set or null if this tree mapset uses its keyselements natural ordering. @return the comparator used to order this sorted set or null if this tree mapset uses its keyselements natural ordering.
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 a given 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, 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 a given 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 NullPointerExceptionClassCastException if fromElement orand toElement iscannot nullbe andcompared to one another using this set's usescomparator natural(or ordering or its comparator does not tolerateif the set has no comparator using nullnatural elementsordering). @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 a given 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 JDK1the 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. @author Lee Boynton @author Jonathan Payne @version 1.6271 04/2218/9900 @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. @since JDK11.2
Class Vector, boolean add(Object)

Appends the specified element to the end of this Vector. @param o element to be appended to this Vector. @return true (as per the general contract of Collection.add). @since JDK11.2
Class Vector, void add(int, Object)

Inserts the specified element at the specified position in this Vector. 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. @exception ArrayIndexOutOfBoundsException index is out of range (index < 0 || index > size()). @since JDK11.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 index index at which to insert first element from the specified collection. @param c elements to be inserted into this Vector. @exception ArrayIndexOutOfBoundsException index out of range (index < 0 || index > size()). @since JDK11.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. @exception ArrayIndexOutOfBoundsException index out of range (index < 0 || index > size()). @since JDK11.2
Class Vector, void clear()

Removes all of the elements from this Vector. The Vector will be empty after this call returns (unless it throws an exception). @since JDK11.2
Class Vector, void ensureCapacity(int)

Increases the capacity of this vector if necessary to ensure that it can hold at least the number of components specified by the minimum capacity argument.

If the current capacity of this vector is less than minCapacity then its capacity is increased by replacing its internal data array kept in the field elementData with a larger one. The size of the new data array will be the old size plus capacityIncrement unless the value of capacityIncrement is nonpositiveless than or equal to zero in which case the new capacity will be twice the old capacity; but if this new size is still smaller than minCapacity then the new capacity will be minCapacity. @param minCapacity the desired minimum capacity.

Class Vector, Object get(int)

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

Searches for the first occurence of the given argument beginning the search at index and testing for equality using the equals method. @param elem an object. @param index the non-negative index to start searching from. @return the index of the first occurrence of the object argument in this vector at position index or later in the vector that is the smallest value k such that elem.equals(elementData[k]) && (k >= index) is true; returns -1 if the object is not found. (Returns -1 if index >= the current size of this Vector.) @exception IndexOutOfBoundsException if index is negative. @see Object#equals(Object)
Class Vector, int lastIndexOf(Object, int)

Searches backwards for the specified object starting from the specified index and returns an index to it. @param elem the desired component. @param index the index to start searching from. @return the index of the last occurrence of the specified object in this vector at position less than or equal to index in the vector that is the largest value k such that elem.equals(elementData[k]) && (k <= index) is true; -1 if the object is not found. (Returns -1 if index is negative.) @exception IndexOutOfBoundsException if index is greater than or equal to the current size of this vector.
Class Vector, boolean remove(Object)

Removes the first occurrence of the specified element in this Vector If the Vector 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 Vector if present. @return true if the Vector contained the specified element. @since JDK11.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. @since JDK11.2
Class Vector, boolean removeAll(Collection)

Removes from this Vector all of its elements that are contained in the specified Collection. @return true if this Vector changed as a result of the call. @since JDK11.2
Class Vector, void removeRange(int, int)

Removes from this List all of the elements whose index is between fromIndex inclusive and toIndex exclusive. Shifts any succeeding elements to the left (reduces their index). This call shortens the ArrayList by (toIndex - fromIndex) elements. (If toIndex==fromIndex this operation has no effect.) @param fromIndex index of first element to be removed. @param fromIndextoIndex index after last element to be removed.
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. @return true if this Vector changed as a result of the call. @since JDK11.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 JDK11.2
Class Vector, 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.) @param fromIndex low endpoint (inclusive) of the subList. @param toKeytoIndex 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 Vector, Object[] toArray()

Returns an array containing all of the elements in this Vector in the correct order. @since JDK11.2
Class Vector, int capacityIncrement

The amount by which the capacity of the vector is automatically incremented when its size becomes greater than its capacity. If the capacity increment is 0less than or equal to zero the capacity of the vector is doubled each time it needs to grow. @serial

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 may be fixed in a future release. @version 1.5 9812 02/0902/3000 @author Mark Reinhold @since JDK11.2 @see java.util.HashMap @see java.lang.ref.WeakReference

Class WeakHashMap, constructor WeakHashMap()

Constructs a new empty WeakHashMap with the default initial capacity and the default load factor which is 0.75.