|
Generated by JDiff |
||||||||
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES |
This file contains all the changes in documentation in the packagejava.util
as colored differences. Deletions are shownlike this, and additions are shown like this.
If no deletions or additions are shown in an entry, the HTML tags will be what has changed. The new HTML tags are shown in the differences. If no documentation existed, and then some was added in a later version, this change is noted in the appropriate class pages of differences, but the change is not shown on this page. Only changes in existing text are shown here. Similarly, documentation which was inherited from another class or interface is not shown here.
Note that an HTML error in the new documentation may cause the display of other documentation changes to be presented incorrectly. For instance, failure to close a <code> tag will cause all subsequent paragraphs to be displayed differently.
This class provides a skeletal implementation of the Collection interface to minimize the effort required to implement this interface.Class AbstractCollection, boolean retainAll(Collection)To implement an unmodifiable collection the programmer needs only to extend this class and provide implementations for the iterator and size methods. (The iterator returned by the iterator method must implement hasNext and next.)
To implement a modifiable collection the programmer must additionally override this class's add method (which otherwise throws an UnsupportedOperationException) and the iterator returned by the iterator method must additionally implement its remove method.
The programmer should generally provide a void (no argument) and Collection constructor as per the recommendation in the Collection interface specification.
The documentation for each non-abstract methods in this class describes its implementation in detail. Each of these methods may be overridden if the collection being implemented admits a more efficient implementation. @author Josh Bloch @version 1.
11 0916 02/3002/9800 @see Collection @sinceJDK11.2
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)
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array). For sequential access data (such as a linked list) AbstractSequentialList should be used in preference to this class.Class AbstractList, List subList(int, int)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 @sinceJDK11.2
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();nSimilar 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)
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 @sinceJDK11.2
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "sequential access" data store (such as a linked list). For random access data (such as an array) AbstractList should be used in preference to this class.Class AbstractSequentialList, Object remove(int)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 @sinceJDK11.2
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()).
This class provides a skeletal implementation of the Set interface to minimize the effort required to implement this interface.Class AbstractSet, int hashCode()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 @sinceJDK11.2
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.Class AbstractSet, boolean removeAll(Collection)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.
Removes from thiscollectionset 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'sis contained in the specified collection. If it'sis so contained it'sis removed from thiscollectionset 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 thiscollectionset changed as a result of the call. @throws UnsupportedOperationException removeAll is not supported by thiscollectionset. @see #remove(Object) @see #contains(Object)
Resizable-array implementation of the List interface. Implements all optional list operations and permits all elements including null. In addition to implementing the List interface this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector except that it is unsynchronized.)Class ArrayList, constructor ArrayList(Collection)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) @sinceJDK11.2
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 negativeClass 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.) @paramClass ArrayList, boolean contains(Object)index index at which to insert first element fromc thespecified collection. @param celements to be inserted into this list. @throws IndexOutOfBoundsException if index out of range (index < 0 || index > size()).
Returns true if this list contains the specified element. @paramClass ArrayList, void removeRange(int, int)oelem element whose presence in this List is to be tested.
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. @paramfromIndextoIndex index after last element to be removed.
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.Class Arrays, int binarySearch(Object[], Object, Comparator)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 @sinceJDK11.2
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.Class Arrays, boolean equals(float[], float[])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)
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.Class Arrays, void fill(Object[], int, int, Object)Two
doublesfloatsd1f1 andd2f2 are considered equal if:new(Unlike the == operator this method considers NaN equals to itself and 0.DoubleFloat(d1f1).equals(newDoubleFloat(d2f2))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. @seeDoubleFloat#equals(DoubleObject)
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.lengthClass 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.lengthClass 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.lengthClass 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.lengthClass 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.lengthClass 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.lengthClass 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.lengthClass 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.lengthClass 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.lengthClass 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).Class Arrays, void sort(Object[], int, int)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
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).Class Arrays, void sort(Object[], int, int, Comparator)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
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).Class Arrays, void sort(byte[], int, int)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
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.)Class Arrays, void sort(char[], int, int)The
sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Sorts the specified 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.)Class Arrays, void sort(double[], int, int)The
sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Sorts the specified range of the specified array of doubles into ascending numerical order. The range to be sorted extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be sorted is empty.)Class Arrays, void sort(float[], int, int)The
sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Sorts the specified 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.)Class Arrays, void sort(int[], int, int)The
sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Sorts the specified 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.)Class Arrays, void sort(long[], int, int)The
sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Sorts the specified 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.)Class Arrays, void sort(short[], int, int)The
sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Sorts the specified 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
This class implements a vector of bits that grows as needed. Each component of the bit set has aClass BitSet, void andNot(BitSet)boolean
value. The bits of aBitSet
are indexed by nonnegative integers. Individual indexed bits can be examined set or cleared. OneBitSet
may be used to modify the contents of anotherBitSet
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
Clears all of the bits in thisClass BitSet, int length()BitSet
whose corresponding bit is set in the specifiedBitSet
. @paramsset theBitSet
with which to mask thisBitSet
. @sinceJDK11.2
Returns the "logical size" of thisBitSet
: the index of the highest set bit in theBitSet
plus one. Returns zero if theBitSet
contains no set bits. @return the logical size of thisBitSet
. @sinceJDK11.2
Class Calendar, int getActualMaximum(int)Calendar
is an abstract base class for converting between aDate
object and a set of integer fields such asYEAR
MONTH
DAY
HOUR
and so on. (ADate
object represents a specific instant in time with millisecond precision. See Date for information about theDate
class.)Subclasses of
Calendar
interpret aDate
according to the rules of a specific calendar system. TheJDKplatform provides one concrete subclass ofCalendar
:GregorianCalendar
. Future subclasses could represent the various types of lunar calendars in use in many parts of the world.Like other locale-sensitive classes
Calendar
provides a class methodgetInstance
for getting a generally useful object of this type.Calendar
'sgetInstance
method returns aGregorianCalendar
object whose time fields have been initialized with the current date and time:Calendar rightNow = Calendar.getInstance();
ACalendar
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 valueMONTH
==JANUARY
for all calendars. Other values are defined by the concrete subclass such asERA
andYEAR
. 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 lenientGregorianCalendar
interpretsMONTH
==JANUARY
DAY_OF_MONTH
== 32 as February 1. A non-lenientGregorianCalendar
throws an exception when given out-of-range field settings. When calendars recompute field values for return byget()
they normalize them. For example aGregorianCalendar
always producesDAY_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 aCalendar
is constructed. They may also be specified explicitly through the API.When setting or getting the
WEEK_OF_MONTH
orWEEK_OF_YEAR
fieldsCalendar
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 ongetFirstDayOfWeek()
and containing at leastgetMinimalDaysInFirstWeek()
days of that month or year. Weeks numbered ... -1 0 precede the first week; weeks numbered 2 3 ... follow it. Note that the normalized numbering returned byget()
may be different. For example a specificCalendar
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 theDate
(such as only year and month but no day in the month) or there may be inconsistent information (such as "Tuesday July 15 1996" -- July 15 1996 is actually a Monday).Insufficient information. The calendar will use default information to specify the missing fields. This may vary by calendar; for the Gregorian calendar the default for a field is the same as that of the start of the epoch: i.e. YEAR = 1970 MONTH = JANUARY DATE = 1 etc.
Inconsistent information. If fields conflict the calendar will give preference to fields set more recently. For example when determining the day the calendar will look for one of the following combinations of fields. The most recent combination as determined by the most recently set single field will be used.
For the time of day:MONTH + DAY_OF_MONTH MONTH + WEEK_OF_MONTH + DAY_OF_WEEK MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK DAY_OF_YEAR DAY_OF_WEEK + WEEK_OF_YEARHOUR_OF_DAY AM_PM + HOURNote: for some non-Gregorian calendars different fields may be necessary for complete disambiguation. For example a full specification of the 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:
- 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
- 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()
androll()
.
set(f value)
changes fieldf
tovalue
. In addition it sets an internal member variable to indicate that fieldf
has been changed. Although fieldf
is changed immediately the calendar's milliseconds is not recomputed until the next call toget()
getTime()
orgetTimeInMillis()
is made. Thus multiple calls toset()
do not trigger multiple unnecessary computations. As a result of changing a field usingset()
other fields may also change depending on the field the field value and the calendar system. In additionget(f)
will not necessarily returnvalue
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. Callingset(Calendar.MONTH Calendar.SEPTEMBER)
sets the calendar to September 31 1999. This is a temporary internal representation that resolves to October 1 1999 ifgetTime()
is then called. However a call toset(Calendar.DAY_OF_MONTH 30)
before the call togetTime()
sets the calendar to September 30 1999 since no recomputation occurs afterset()
itself.
add(f delta)
addsdelta
to fieldf
. This is equivalent to callingset(f get(f) + delta)
with two adjustments:Add rule 1. The value of field
f
after the call minus the value of fieldf
before the call isdelta
modulo any overflow that has occurred in fieldf
. Overflow occurs when a field value exceeds its range and as a result the next larger field is incremented or decremented and the field value is adjusted back into its range.Add rule 2. If a smaller field is expected to be invariant but it is impossible for it to be equal to its prior value because of changes in its minimum or maximum after field
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 thanDAY_OF_MONTH
. No adjustment is made to smaller fields that are not expected to be invariant. The calendar system determines what fields are expected to be invariant.In addition unlike
set()
add()
forces an immediate recomputation of the calendar's milliseconds and all fields.Example: Consider a
GregorianCalendar
originally set to August 31 1999. Callingadd(Calendar.MONTH 13)
sets the calendar to September 30 2000. Add rule 1 sets theMONTH
field to September since adding 13 months to August gives September of the next year. SinceDAY_OF_MONTH
cannot be 31 in September in aGregorianCalendar
add rule 2 sets theDAY_OF_MONTH
to 30 the closest possible value. Although it is a smaller fieldDAY_OF_WEEK
is not adjusted by rule 2 since it is expected to change when the month changes in aGregorianCalendar
.
roll(f delta)
addsdelta
to fieldf
without changing larger fields. This is equivalent to callingadd(f delta)
with the following adjustment:Roll rule. Larger fields are unchanged after the call. A larger field represents a larger unit of time.
DAY_OF_MONTH
is a larger field thanHOUR
.Example: Consider a
GregorianCalendar
originally set to August 31 1999. Callingroll(Calendar.MONTH 8)
sets the calendar to April 30 1999. Add rule 1 sets theMONTH
field to April. Using aGregorianCalendar
theDAY_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 theYEAR
field value of 1999.Example: Consider a
GregorianCalendar
originally set to Sunday June 6 1999. Callingroll(Calendar.WEEK_OF_MONTH -1)
sets the calendar to Tuesday June 1 1999 whereas callingadd(Calendar.WEEK_OF_MONTH -1)
sets the calendar to Sunday May 30 1999. This is because the roll rule imposes an additional constraint: TheMONTH
must not change when theWEEK_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 theDAY_OF_WEEK
an invariant when changing theWEEK_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
@see Date @see GregorianCalendar @see TimeZone @see java.text.DateFormat @version 1.add()
androll()
consider a user interface component with increment and decrement buttons for the month day and year and an underlyingGregorianCalendar
. If the interface reads January 31 1999 and the user presses the month increment button what should it read If the underlying implementation usesset()
it might read March 3 1999. A better result would be February 28 1999. Furthermore if the user presses the month increment button again it should read March 31 1999 not March 28 1999. By saving the original date and using eitheradd()
orroll()
depending on whether larger fields should be affected the user interface can behave as most users will intuitively expect.4449 01/19/00 @author Mark Davis David Goldsmith Chen-Lieh Huang Alan Liu @since JDK1.1
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.2Class 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.2Class Calendar, int hashCode()
Returns a hash code for this calendar. @return a hash code value for this object. @since 1.2Class 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.2Class Calendar, int DATE
Field number forClass Calendar, int DAY_OF_MONTHget
andset
indicating the day of the month. This is a synonym forDAY_OF_MONTH
. The first day of the month has value 1. @see #DAY_OF_MONTH
Field number forClass Calendar, int DAY_OF_WEEKget
andset
indicating the day of the month. This is a synonym forDATE
. The first day of the month has value 1. @see #DATE
Field number forClass Calendar, int DAY_OF_WEEK_IN_MONTHget
andset
indicating the day of the week. This field takes valuesSUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
andSATURDAY
. @see #SUNDAY @see #MONDAY @see #TUESDAY @see #WEDNESDAY @see #THURSDAY @see #FRIDAY @see #SATURDAY
Field number forClass Calendar, int DAY_OF_YEARget
andset
indicating the ordinal number of the day of the week within the current month. Together with theDAY_OF_WEEK
field this uniquely specifies a day within a month.Example:UnlikeWEEK_OF_MONTH
andWEEK_OF_YEAR
this field's value does not depend ongetFirstDayOfWeek()
orgetMinimalDaysInFirstWeek()
.DAY_OF_MONTH 1
through7
always correspond toDAY_OF_WEEK_IN_MONTH 1
;8
through15
correspond toDAY_OF_WEEK_IN_MONTH 2
and so on.DAY_OF_WEEK_IN_MONTH 0
indicates the week beforeDAY_OF_WEEK_IN_MONTH 1
. Negative values count back from the end of the month so the last Sundayinof aOctobermonth is specified asDAY_OF_WEEK =
. Because negative values count backward they will usually be aligned differently within the month than positive values. For example if a month has 31 daysSundaySUNDAY DAY_OF_WEEK_IN_MONTH = -1DAY_OF_WEEK_IN_MONTH -1
will overlapDAY_OF_WEEK_IN_MONTH 5
and the end of4
. @see #DAY_OF_WEEK @see #WEEK_OF_MONTH
Field number forClass Calendar, int ERAget
andset
indicating the day number within the current year. The first day of the year has value 1.
Field number forClass Calendar, int MONTHget
andset
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
Field number forClass Calendar, int WEEK_OF_MONTHget
andset
indicating the month. This is a calendar-specific value. The first month of the year isJANUARY
; the last depends on the number of months in a year. @see #JANUARY @see #FEBRUARY @see #MARCH @see #APRIL @see #MAY @see #JUNE @see #JULY @see #AUGUST @see #SEPTEMBER @see #OCTOBER @see #NOVEMBER @see #DECEMBER @see #UNDECIMBER
Field number forClass Calendar, int WEEK_OF_YEARget
andset
indicating the week number within the current month. The first week of the month as defined bygetFirstDayOfWeek()
andgetMinimalDaysInFirstWeek()
has value 1. Subclasses define the value ofWEEK_OF_MONTH
for days before the first week of the month. @see #getFirstDayOfWeek @see #getMinimalDaysInFirstWeek
Field number forClass Calendar, int YEARget
andset
indicating the week number within the current year. The first week of the year as defined bygetFirstDayOfWeek()
andgetMinimalDaysInFirstWeek()
has value 1. Subclasses define the value ofWEEK_OF_YEAR
for days before the first week of the year. @see #getFirstDayOfWeek @see #getMinimalDaysInFirstWeek
Field number forget
andset
indicating the year. This is a calendar-specific value; see subclass documentation.
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. TheClass Collection, boolean isEmpty()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 @sinceJDK11.2
Returns true if this collection contains no elements. @Class Collection, Iterator iterator()returnsreturn true if this collection contains no elements
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). @Class Collection, Object[] toArray(Object[])returnsreturn an Iterator over the elements in this collection
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.
This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections "wrappers" which return a new collection backed by a specified collection and a few other odds and ends.Class Collections, int binarySearch(List, Object, Comparator)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 @sinceJDK11.2
Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the specified comparator (as by the Sort(List Comparator) method above) prior to making this call. If it is not sorted the results are undefined. If the list contains multiple elements equal to the specified object there is no guarantee which one will be found.Class Collections, Object max(Collection, Comparator)This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access). It may run in n log(n) time if it is called on 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)
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).Class Collections, Object min(Collection, Comparator)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
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).Class Collections, void reverse(List)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
Reverses the order of the elements in the specified list.Class Collections, void shuffle(List, Random)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.
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.Class Collections, Set singleton(Object)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.
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
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).Class Comparator, int compare(Object, Object)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 @sinceJDK11.2
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.
This exception may be thrown by methods that have detected concurrent modification of a backing object when such modification is not permissible.Class ConcurrentModificationException, constructor ConcurrentModificationException(String)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.6110902/3002/9800 @see Collection @see Iterator @see ListIterator @see Vector @see LinkedList @see HashSet @see Hashtable @see TreeMap @see AbstractList @sinceJDK11.2
Constructs a ConcurrentModificationException with the specified detail message. @param message the detail message pertaining to this exception.
The classClass Date, int compareTo(Date)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 theCalendar
class should be used to convert between dates and time fields and theDateFormat
class should be used to format and parse date strings. The corresponding methods inDate
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.miland their definitions of "Systems of Time" at:
http://tycho.usno.navy.mil/systime.htmlIn all methods of class
Date
that accept or return year month date hours minutes and seconds values the following representations are used:
- A year y is represented by the integer y
- 1900
.- A month is represented by an integer form 0 to 11; 0 is January 1 is February and so forth; thus 11 is December.
- A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
- An hour is represented by an integer from 0 to 23. Thus the hour from midnight to 1 a.m. is hour 0 and the hour from noon to 1 p.m. is hour 12.
- A minute is represented by an integer from 0 to 59 in the usual manner.
- A second is represented by an integer from 0 to 61; the values 60 and 61 occur only for leap seconds and even then only in Java implementations that actually track leap seconds correctly. Because of the manner in which leap seconds are currently introduced it is extremely unlikely that two leap seconds will occur in the same minute but this specification follows the date and time conventions for ISO C.
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
Compares two Dates for ordering. @param anotherDate theClass Date, int compareTo(Object)Date
to be compared. @return the value0
if the argument Date is equal to this Date; a value less than0
if this Date is before the Date argument; and a value greater than0
if this Date is after the Date argument. @sinceJDK11.2
Compares this Date to another Object. If the Object is a Date this function behaves likeClass Date, long parse(String)compareTo(Date)
. Otherwise it throws aClassCastException
(as Dates are comparable only to other Dates). @param o theObject
to be compared. @return the value0
if the argument is a Date equal to this Date; a value less than0
if the argument is a Date after this Date; and a value greater than0
if the argument is a Date before this Date. @exception ClassCastException if the argument is not aDate
. @see java.lang.Comparable @sinceJDK11.2
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.Class Date, String toLocaleString()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:
and whitespace characters.abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 +-:/A consecutive sequence of decimal digits is treated as a decimal number:
- If a number is preceded by + or - and a year has already been recognized then the number is a time-zone offset. If the number is less than 24 it is an offset measured in hours. Otherwise it is regarded as an offset in minutes expressed in 24-hour time format without punctuation. A preceding - means a westward offset. Time zone offsets are always relative to UTC (Greenwich). Thus for example -5 occurring in the string would mean "five hours west of Greenwich" and +0430 would mean "four hours and thirty minutes east of Greenwich." It is permitted for the string to specify GMT UT or UTC redundantly-for example GMT-5 or utc+0430.
- The number is regarded as a year number if one of the following conditions is true:
If the recognized year number is less than 100 it is interpreted as an abbreviated year relative to a century of which dates are within 80 years before and 19 years after the time when the Date class is initialized. After adjusting the year number 1900 is subtracted from it. For example if the current year is 1999 then years in the range 19 to 99 are assumed to mean 1919 to 1999 while years from 0 to 18 are assumed to mean 2000 to 2018. Note that this is slightly different from the interpretation of years less than 100 that is used in java.text.
- The number is equal to or greater than 70 and followed by a space comma slash or end of string
- The number is less than 70 and both a month and a day of the month have already been recognized
SimpleDateFomatSimpleDateFormat- If the number is followed by a colon it is regarded as an hour unless an hour has already been recognized in which case it is regarded as a minute.
- If the number is followed by a slash it is regarded as a month (it is decreased by 1 to produce a number in the range 0 to 11) unless a month has already been recognized in which case it is regarded as a day of the month.
- If the number is followed by whitespace a comma a hyphen or end of string then if an hour has been recognized but not a minute it is regarded as a minute; otherwise if a minute has been recognized but not a second it is regarded as a second; otherwise it is regarded as a day of the month.
A consecutive sequence of letters is regarded as a word and treated as follows:
- A word that matches AM ignoring case is ignored (but the parse fails if an hour has not been recognized or is less than 1 or greater than 12).
- A word that matches PM ignoring case adds 12 to the hour (but the parse fails if an hour has not been recognized or is less than 1 or greater than 12).
- Any word that matches any prefix of SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY or SATURDAY ignoring case is ignored. For example sat Friday TUE and Thurs are ignored.
- Otherwise any word that matches any prefix of JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY AUGUST SEPTEMBER OCTOBER NOVEMBER or DECEMBER ignoring case and considering them in the order given here is recognized as specifying a month and is converted to a number (0 to 11). For example aug Sept april and NOV are recognized as months. So is Ma which is recognized as MARCH not MAY.
- Any word that matches GMT UT or UTC ignoring case is treated as referring to UTC.
- Any word that matches EST CST MST or PST ignoring case is recognized as referring to the time zone in North America that is five six seven or eight hours west of Greenwich respectively. Any word that matches EDT CDT MDT or PDT ignoring case is recognized as referring to the same time zone respectively during daylight saving time.
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)
.
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 thestrftime()
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 byDateFormat.format(Date date)
.
TheDictionary
class is the abstract parent of any class such asHashtable
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
Thrown by methods in theStack
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
An object that implements the Enumeration interface generates a series of elements one at a time. Successive calls to thenextElement
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
A tagging interface that all event listener interfaces must extend. @since JDK1.1
The
Event class is the abstractroot 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, int getActualMaximum(int)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 resultGregorianCalendar
may be used for all years to generate meaningful and consistent results. However dates obtained usingGregorianCalendar
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 thefirstearliestweekseven day period starting ongetFirstDayOfWeek()
that contains at leastgetMinimalDaysInFirstWeek()
days from that year. It thus depends on the values ofgetMinimalDaysInFirstWeek()
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()
isMONDAY
andgetMinimalDaysInFirstWeek()
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 howevergetFirstDayOfWeek()
isSUNDAY
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 withWEEK_OF_MONTH = 1
) is the earliest set of at leastgetMinimalDaysInFirstWeek()
contiguous days in that month ending on the day beforegetFirstDayOfWeek()
. Unlike week 1 of a year week 1 of a month may be shorter than 7 days need not start ongetFirstDayOfWeek()
and will not include days of the previous month. Days of a month before week 1 have aWEEK_OF_MONTH
of 0.For example if
Example:getFirstDayOfWeek()
isSUNDAY
andgetMinimalDaysInFirstWeek()
is 4 then the first week of January 1998 is Sunday January 4 through Saturday January 10. These days have aWEEK_OF_MONTH
of 1. Thursday January 1 through Saturday January 3 have aWEEK_OF_MONTH
of 0. IfgetMinimalDaysInFirstWeek()
is changed to 3 then January 1 through January 3 have aWEEK_OF_MONTH
of 1.@see Calendar @see TimeZone @version 1.// 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 hours4753 @author David Goldsmith Mark Davis Chen-Lieh Huang Alan Liu @since JDK1.1
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.2Class 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.2Class GregorianCalendar, void roll(int, int)
Roll a field by a signed amount. @since 1.2
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.Class HashMap, constructor HashMap(Map)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.
29380402/2202/9900 @see Object#hashCode() @see Collection @see Map @see TreeMap @see Hashtable @sinceJDK11.2
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.
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.Class HashSet, constructor HashSet(Collection)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 @sinceJDK11.2
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.
This class implements a hashtable which maps keys to values. Any non-Class Hashtable, constructor Hashtable(Map)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 theequals
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 therehash
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. Norehash
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
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. @sinceClass Hashtable, boolean containsValue(Object)JDK11.2
Returns true if this Hashtable maps one or more keys to this value.Class Hashtable, Set entrySet()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
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 @sinceClass Hashtable, boolean equals(Object)JDK11.2
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) @sinceClass Hashtable, int hashCode()JDK11.2
Returns the hash code value for this Map as per the definition in the Map interface. @see Map#hashCode() @sinceClass Hashtable, Set keySet()JDK11.2
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. @sinceClass Hashtable, void putAll(Map)JDK11.2
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. @sinceClass Hashtable, Collection values()JDK11.2
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. @sinceJDK11.2
An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:Class Iterator, Object next()@author Josh Bloch @version 1.
- Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
- Method names have been improved.
9 0914 02/3002/9800 @see Collection @see ListIterator @see Enumeration @sinceJDK11.2
Returns the next element in the interation. @returnsreturn the next element in theinterationiteration. @exception NoSuchElementException iteration has no more elements.
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).Class LinkedList, constructor LinkedList(Collection)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) @sinceJDK11.2
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.) @paramClass LinkedList, void addFirst(Object)index index at which to insert first element fromc thespecified collection. @param celements to be inserted into this list. @throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()).
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.
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.Class List, boolean contains(Object)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 @sinceJDK11.2
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. @Class List, List subList(int, int)returnsreturn true if this list contains the specified element.
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).
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.Class ListIterator, void add(Object)11 0916 02/3002/9800 @see Collection @see List @see Iterator @see Enumeration @sinceJDK11.2
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.
ListResourceBundle
is a abstract subclass ofResourceBundle
that manages resources for a locale in a convenient and easy to use list. SeeResourceBundle
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 aString
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 andMyResource_fr
is the french version:@see ResourceBundle @see PropertyResourceBundle @since JDK1.1//==================== 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 }; }
AClass Locale, constructor Locale(String, String)Locale
object represents a specific geographical political or cultural region. An operation that requires aLocale
to perform its task is called locale-sensitive and uses theLocale
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: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:Locale(String language String country) Locale(String language String country String variant)
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 aLocale
. If you want to see whether particular resources are available for theLocale
you construct you must query those resources. For example ask theNumberFormat
for the locales it supports using itsgetAvailableLocales
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 ResourceBundleThe
Locale
class provides a number of convenient constants that you can use to createLocale
objects for commonly used locales. For example the following creates aLocale
object for the United States:Locale.USOnce you've created a
Locale
you can query it for information about itself. UsegetCountry
to get the ISO Country Code andgetLanguage
to get the ISO Language Code. You can usegetDisplayCountry
to get the name of the country suitable for displaying to the user. Similarly you can usegetDisplayLanguage
to get the name of the language suitable for displaying to the user. Interestingly thegetDisplayXXX
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 theNumberFormat
class formats numbers currency or percentages in a locale-sensitive manner. Classes such asNumberFormat
have a number of convenience methods for creating a default object of that type. For example theNumberFormat
class provides these three convenience methods for creating a defaultNumberFormat
object:These methods have two variants; one with an explicit locale and one without; the latter using the default locale.NumberFormat.getInstance() NumberFormat.getCurrencyInstance() NumberFormat.getPercentInstance()ANumberFormat.getInstance(myLocale) NumberFormat.getCurrencyInstance(myLocale) NumberFormat.getPercentInstance(myLocale)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:
@see ResourceBundle @see java.text.Format @see java.text.NumberFormat @see java.text.Collator @version 1.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.21 2955Jan 199701/19/00 @author Mark Davis @since JDK1.1
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()Class Locale, String getISO3Language()CommonGetsmethod of gettingthe currentdefault Locale. Usedvalueforof thepresentation: menus dialogs etc. Generally setdefaultonce when your applet or application is initializedlocale for this instance of the Java VirtualthenMachine.never
reset.The(IfJavayou do resetVirtual Machine sets the default localeyou probably wantduringto reload yourstartup based onGUI so thatthechangehostisenvironment.reflected in yourIt is usedinterface.)byMoremanyadvancedlocale-sensitiveprograms will allow users to usemethods if no locale is explicitlydifferentspecified.locales for different fieldsIt can be changede.g.usingintheasetDefaultspreadsheetmethod.Note@returnthattheinitialdefault locale forsetting will matchthis instance of thehostJavasystem.Virtual Machine
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 forthe whole JVM. Normally set once at thethisbeginninginstance ofan applicationthethen never resetJava Virtual Machine.setDefaultThis does notresetaffect the host locale.If there is a security manager its
checkPermission
method is called with aPropertyPermission("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 itscheckPermission
method doesn't allow the operation. @throws NullPointerException ifnewLocale
is null @param newLocaleThethe new defaultLocale.locale @see SecurityManager#checkPermission @see java.util.PropertyPermission
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.27320902/3002/9800 @see HashMap @see TreeMap @see Hashtable @see SortedMap @see Collection @see Set @sinceJDK11.2
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
Signals that a resource is missing. @see java.iolang.Exception @see ResourceBundle @version 1.9120901/2119/9800 @author Mark Davis @since JDK1.1
Thrown by thenextElement
method of anEnumeration
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
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.Class Observable, constructor Observable()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
'snotifyObservers
method causes all of its observers to be notified of the change by a call to theirupdate
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
Construct an Observable with zero Observers.Class Observable, void notifyObservers()
If this object has changed as indicated by thehasChanged
method then notify all of its observers and then call theclearChanged
method to indicate that this object has no longer changed.Each observer has its
update
method called with two arguments: this observable object andnull
. In other words this method is equivalent to:@see java.util.Observable#clearChanged() @see java.util.Observable#hasChanged() @see java.util.Observer#update(java.util.Observable java.lang.Object)notifyOvserversnotifyObservers(null)
A class can implement theObserver
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
TheClass Properties, String getProperty(String)Properties
class represents a persistent set of properties. TheProperties
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 fromHashtable
theput
andputAll
methods can be applied to aProperties
object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are notStrings
. ThesetProperty
method should be used instead. If thestore
orsave
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
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 returnsClass Properties, String getProperty(String, String)null
if the property is not found. @param key the property key. @return the value in this property list with the specified key value. @seejava.util.Properties#setProperty @see #defaults
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. @seeClass Properties, void load(InputStream)java.util.Properties#setProperty @see #defaults
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.Class Properties, void save(OutputStream, String)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
#
oris ignored (thus
#
orindicate 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) andxxxx are recognized and converted to single characters. Moreover if the last character on the line is
\\\u\
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 :BeautyAs another example the following three lines specify a single property:
fruits apple banana pear \ cantaloupe watermelon \ kiwi mangoThe 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:
cheesesspecifies 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.
Calls theClass Properties, Object setProperty(String, String)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 ofJDKthe Java 2 platform1v1.2 the preferred way to save a properties list is via thestore(OutputStream out String header)
method. @param out an output stream. @param header a description of the property list. @exception ClassCastException if thisProperties
object contains any keys or values that are notStrings
.
Calls the hashtable methodClass Properties, void store(OutputStream, String)put
. Provided for parallelism with thegetPropertiesgetProperty 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 @sinceJDK11.2
Writes this property list (key and element pairs) in thisProperties
table to the output stream in a format suitable for loading into aProperties
table using theload
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 theheader
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 thetoString
method ofDate
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 thanand characters greater than
\u0020are written as
~\u007Exxxx for the appropriate hexadecimal value xxxx.
\\\uSpaceLeading 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 notStrings
.
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
PropertyResourceBundle
is a concrete subclass ofResourceBundle
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 ingeneralparticular 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 aPropertyResourceBundle
that refers to it. The resource bundle name that you pass toResourceBundle.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 calledMyResources_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.
@see ResourceBundle @see ListResourceBundle @see Properties @since JDK1.1s1=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
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.)Class Random, boolean nextBoolean()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 classMath
simpler to use. @author Frank Yellin @version 1.27 0434 02/2202/9900 @see java.lang.Math#random() @since JDK1.0
Returns the next pseudorandom uniformly distributedClass Random, double nextGaussian()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 valuestrue
andfalse
are produced with (approximately) equal probability. The method nextBoolean is implemented by class Random as follows:@return the next pseudorandom uniformly distributedpublic boolean nextBoolean() {return next(1) = 0;}boolean
value from this random number generator's sequence. @sinceJDK11.2
Returns the next pseudorandom Gaussian ("normally") distributedClass Random, int nextInt(int)double
value with mean0.0
and standard deviation1.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:
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") distributedsynchronized 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; } }
double
value with mean0.0
and standard deviation1.0
from this random number generator's sequence.
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. @sinceJDK11.2
Resource bundles contain locale-specific objects. When your program needs a locale-specific resource aClass ResourceBundle, ResourceBundle getBundle(String, Locale, ClassLoader)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:
- be easily localized or translated into different languages
- handle multiple locales at once
- be easily modified later to support even more locales
One resource bundle is conceptually a set of related classes that inherit from
ResourceBundle
. Each related subclass ofResourceBundle
has the same base name plus an additional component that identifies its locale. For example suppose your resource bundle is namedMyResources
. 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 namedMyResources_de
.Each related subclass of
ResourceBundle
contains the same items but the items have been translated for the locale represented by thatResourceBundle
subclass. For example bothMyResources
andMyResources_de
may have aString
that's used on a button forconfirmingcanceling operations. InMyResources
theString
may containand in
OKCancelMyResources_de
it may contain.
GutAbbrechenIf 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 thegetBundle
method:The first argument specifies the family name of the resource bundle that contains the object in question. The second argument indicates the desired locale.ResourceBundle myResources = ResourceBundle.getBundle("MyResources" currentLocale);getBundle
uses these two arguments to construct the name of theResourceBundle
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
MyResourcesThe 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 failsgetBundle()
throws aMissingResourceException
.The baseclass must be fully qualified (for example
myPackage.MyResources
not justMyResources
). It must also be accessable by your code; it cannot be a class that is private to the package whereResourceBundle.getBundle
is called.Note:
ResourceBundle
s are used internally in accessingNumberFormat
sCollation
s 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:Keys are alwaysclass MyResource extends ListResourceBundle { public Object[][] getContents() { return contents; } static final Object[][] contents = { // LOCALIZE THIS {"OkKey" "OK"} {"CancelKey" "Cancel"} // END OF MATERIAL TO LOCALIZE }; }String
s. In this example the keys areOkKey
andCancelKey
. In the above example the values are alsoString
s--OK
andCancel
--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
andCancelKey
are both strings you would usegetString
to retrieve them: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 abutton1 = new Button(myResourceBundle.getString("OkKey")); button2 = new Button(myResourceBundle.getString("CancelKey"));MissingResourceException
.Besides
getString
; ResourceBundle supports a number of other methods for getting different types of objects such asgetStringArray
. If you don't have an object that matches one of these methods you can usegetObject
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 ofResourceBundle
ListResourceBundle
andPropertyResourceBundle
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 exampleListResourceBundle
manages its resource as a List of key/value pairs.PropertyResourceBundle
uses a properties file to manage its resources.If
ListResourceBundle
orPropertyResourceBundle
do not suit your needs you can write your ownResourceBundle
subclass. Your subclasses must override two methods:handleGetObject
andgetKeys()
.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 aHashtable
). Notice that if the key is not foundhandleGetObject
must return null. If the key isnull
aNullPointerException
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:
You do not have to restrict yourself to using a single family of// 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; } }ResourceBundle
s. For example you could have a set of bundles for exception messagesExceptionResources
(ExceptionResources_fr
ExceptionResources_de
...) and one for widgetsWidgetResource
(WidgetResources_fr
WidgetResources_de
...); breaking up the resources however you like. @see ListResourceBundle @see PropertyResourceBundle @see MissingResourceException @since JDK1.1
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 ifClass ResourceBundle, String getString(String)key
isnull
.
Get an object from a ResourceBundle.Class ResourceBundle, String[] getStringArray(String)
Convenience method to save casting. @param key see class description. @exception NullPointerException ifkey
isnull
.
Get an object from a ResourceBundle.Class ResourceBundle, Object handleGetObject(String)
Convenience method to save casting. @param key see class description. @exception NullPointerException ifkey
isnull
.
Get an object from a ResourceBundle. NOTE: Subclasses must override. @param key see class description. @exception NullPointerException ifkey
isnull
.
A collection that contains no duplicate elements. More formally sets contain no pair of elementsClass Set, boolean contains(Object)e1
ande2
such thate1.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 @sinceJDK11.2
Returns true if this set contains the specified element. More formally returns true if and only if this set contains an elemente
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, constructor SimpleTimeZone(int, String, int, int, int, int, int, int, int, int)SimpleTimeZone
is a concrete subclass ofTimeZone
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 thatSimpleTimeZone
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
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.1Class 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.2Class 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.2Class SimpleTimeZone, int getOffset(int, int, int, int, int, int)
Class SimpleTimeZone, boolean hasSameRules(TimeZone)OverridesReturnsTimeZone Gets offset for current datethemodifieddifference incase of daylight savings. This is themillisecondsoffset to addbetween local time*to*and UTCto gettakinglocalintotime.accountGetsboth thetime zoneraw offsetfor current date modifiedandin casethe effect of daylight savings. Thisisfor theoffset to add *to* UTC tospecifiedget localdate and time.AssumeThis method assumes that the start and end month are distinct.This methodItmay return incorrect resultsalso uses a defaultforGregorianCalendarrules that start at the end of Februaryobject as its underlying calendar such as for(e.g.determininglastleapSundayyears.inDoFebruary)notoruse thebeginningresult ofMarchthis(e.g.methodMarchwith1)a calendar other than a defaultGregorianCalendar
.ToNote:
avoid such inaccuraciesIn general clients should useCalendar.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 Theoffsetmilliseconds to add*to*GMTUTC to get local time. @exception IllegalArgumentException the era month day dayOfWeek or millis parameters are out of range
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.2Class 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.2Class 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.2Class 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.2Class 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.2Class 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
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.)Class SortedMap, SortedMap headMap(Object)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.7120902/3002/9800 @see Map @see TreeMap @see SortedSet @see Comparator @see Comparable @see Collection @see ClassCastException @sinceJDK11.2
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.Class SortedMap, SortedMap subMap(Object, Object)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 toKeycannot be comparedis not compatible withthethiskeysmap'scurrentlycomparatorin(orthe sortedif the map has no comparator if toKey does not implement Comparable).(Implementations may but are not required to throw this exceptionunderif toKey cannot be compared to keys currently in the map. @throws IllegalArgumentException if this map is itself a subMap headMap or tailMaptheseand toKey is not within the specifiedcircumstancesrange of the subMap headMap or tailMap.)@throws NullPointerException if toKey is null and this sorted map does not tolerate null keys.
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.Class SortedMap, SortedMap tailMap(Object)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 fromKeyorand toKey cannot be comparedwithtothe keys currently inone another using thisthemap'ssortedcomparator (or if the map has no comparator using natural ordering).(Implementations may but are not required to throw this exceptionunderif fromKey or toKey cannot be compared to keys currently inthese circumstancesthe map.)@throwsNullPointerExceptionIllegalArgumentException if fromKeyoris greater than toKey; or if this map isnullitselfand this sorted map does nota subMap headMap or tailMap andtoleratefromKey ornulltoKeykeysare not within the specified range of the subMap headMap or tailMap. @throwsIllegalArgumentExceptionNullPointerException if fromKey or toKey isgreaternullthanand this sorted map does not toleratetoKeynull keys.
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 fromKeycannot be comparedis not compatible withthethiskeysmap'scurrentlycomparatorin(orthe sortedif the map has no comparator if fromKey does not implement Comparable).(Implementations may but are not required to throw this exceptionunderif fromKey cannot be compared to keys currently inthese 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.
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.)Class SortedSet, SortedSet headSet(Object)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.10150402/2202/9900 @see Set @see TreeSet @see SortedMap @see Collection @see Comparable @see Comparator @see java.lang.ClassCastException @sinceJDK11.2
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.Class SortedSet, SortedSet subSet(Object, Object)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 toElementcannot be comparedis not compatible withthethiselementsset'scurrentlycomparatorin(orthe sortedif the set has no comparator if toElement does not implement Comparable).(Implementations may but are not required to throw this exceptionunderif toElement cannot be compared to elements currently inthese 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.
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.Class SortedSet, SortedSet tailSet(Object)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 fromElementorand toElement cannot be comparedwithtothe elements currently inone another using thistheset'ssortedcomparator (or if the set has no comparator using natural ordering).(Implementations may but are not required to throw this exceptionunderif fromElement or toElement cannot be compared to elements currently inthese circumstancesthe set.)@throwsNullPointerExceptionIllegalArgumentException if fromElementoris greater than toElement; or if this set isnullitselfand this sorted set does nota subSet headSet or tailSet andtoleratefromElement ornulltoElementelementsare not within the specified range of the subSet headSet or tailSet. @throwsIllegalArgumentExceptionNullPointerException if fromElement or toElement isgreaternullthanand this sorted set does not toleratetoElementnull elements.
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 fromElementcannot be comparedis not compatible withthethiselementsset'scurrentlycomparatorin(orthe sortedif the set has no comparator if fromElement does not implement Comparable).(Implementations may but are not required to throw this exceptionunderif fromElement cannot be compared to elements currently inthese 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.
TheStack
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
The string tokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by theClass StringTokenizer, constructor StringTokenizer(String)StreamTokenizer
class. TheStringTokenizer
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 theflag having the value
returnTokensreturnDelimstrue
orfalse
:
- If the flag is
false
delimiter characters serve to separate tokens. A token is a maximal sequence of consecutive characters that are not delimiters.- If the flag is
true
delimiter characters are themselves considered to be tokens. A token is thus either one delimiter character or a maximal sequence of consecutive characters that are not delimiters.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:
@author unascribed @version 1.this is a test19250302/1802/9800 @see java.io.StreamTokenizer @since JDK1.0
Constructs a string tokenizer for the specified string. The tokenizer uses the default delimiter set which is " \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 thedelim
argument are the delimiters for separating tokens.If the
flag is
returnTokensreturnDelimstrue
then the delimiter characters are also returned as tokens. Each delimiter is returned as a string of length one. If the flag isfalse
the delimiter characters are skipped and only serve as separators between tokens. @param str a string to be parsed. @param delim the delimiters. @paramreturnTokensreturnDelims flag indicating whether to return the delimiters as tokens.
Class TimeZone, String getDisplayName()TimeZone
represents a time zone offset and also figures out daylight savings.Typically you get a
TimeZone
usinggetDefault
which creates aTimeZone
based on the time zone where the program is running. For example for a program running in JapangetDefault
creates aTimeZone
object based on Japanese Standard Time.You can also get a
TimeZone
usinggetTimeZone
along with a time zone ID. For instance the time zone ID for thePacificU.S.StandardPacific Time zone is "PSTAmerica/Los_Angeles". So you can get aPSTU.S. Pacific TimeTimeZone
object with:You can useTimeZone tz = TimeZone.getTimeZone("PSTAmerica/Los_Angeles");getAvailableIDs
method to iterate through all the supported time zone IDs. You can then choose a supported ID to get aTimeZone
. 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:For example you might specify GMT+14:00 as a custom time zone ID. TheGMT[+|-]hh[[:]mm]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
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 formatClass TimeZone, String getDisplayName(boolean, int, Locale)GMT[+-]hh:mm
. @param daylight if true return the daylight savings name. @param style eitherLONG
orSHORT
@return the human-readable name of this time zone in the default locale. @since 1.2
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 formatClass TimeZone, TimeZone getTimeZone(String)GMT[+-]hh:mm
. @param daylight if true return the daylight savings name. @param style eitherLONG
orSHORT
@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
Gets theClass TimeZone, boolean hasSameRules(TimeZone)TimeZone
for the given ID. @param ID the ID for aTimeZone
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 specifiedTimeZone
or the GMT zone if the given ID cannot be understood.
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 theClass TimeZone, void setDefault(TimeZone)TimeZone
object to be compared with @return true if thegivenother zone is not null and is the same as this one with the possible exception of the ID @since 1.2
Sets theClass TimeZone, int LONGTimeZone
that is returned by thegetDefault
method. Ifzone
is null reset the default to the value it had originally when the VM first started. @param zone the new default time zone
A style specifier for getDisplayName()
indicating a long name such as "Pacific Standard Time." @see #SHORT @since 1.2
Class TimeZone, int SHORTA style specifier for getDisplayName()
indicating a short name such as "PST." @see #LONG @since 1.2
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
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.Class TreeMap, constructor TreeMap(Comparator)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.
33430402/2202/9900 @see Map @see HashMap @see Hashtable @see Comparable @see Comparator @see Collection @see Collections#synchronizedMap(Map) @sinceJDK11.2
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. @sinceClass TreeMap, SortedMap headMap(Object)JDK11.2
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.Class TreeMap, void putAll(Map)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.
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. @paramClass TreeMap, SortedMap subMap(Object, Object)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.
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.Class TreeMap, SortedMap tailMap(Object)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. @throwsNullPointerExceptionClassCastException if fromKeyorand toKeyiscannotnullbeandcompared to one another using this map'susescomparatornatural(ororder or its comparator does not tolerateif the map has no comparator usingnullnaturalkeysordering). @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.
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 naturalorderingorder or its comparator does not tolerate null keys.
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.Class TreeSet, constructor TreeSet(Comparator)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 @sinceJDK11.2
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 treeClass TreeSet, SortedSet headSet(Object)mapset uses itskeyselements natural ordering. @return the comparator used to order this sorted set or null if this treemapset uses itskeyselements natural ordering.
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.Class TreeSet, SortedSet subSet(Object, Object)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.
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.Class TreeSet, SortedSet tailSet(Object)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. @throwsNullPointerExceptionClassCastException if fromElementorand toElementiscannotnullbeandcompared to one another using this set'susescomparatornatural(orordering or its comparator does not tolerateif the set has no comparator usingnullnaturalelementsordering). @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.
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.
TheClass Vector, constructor Vector(Collection)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 aVector
can grow or shrink as needed to accommodate adding and removing items after theVector
has been created.Each vector tries to optimize storage management by maintaining a
capacity
and acapacityIncrement
. Thecapacity
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 ofcapacityIncrement
. 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
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. @sinceClass Vector, boolean add(Object)JDK11.2
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). @sinceClass Vector, void add(int, Object)JDK11.2
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()). @sinceClass Vector, boolean addAll(Collection)JDK11.2
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.) @paramClass Vector, boolean addAll(int, Collection)index index at which to insert first element from the specified collection. @paramc elements to be inserted into this Vector. @exception ArrayIndexOutOfBoundsException index out of range (index < 0 || index > size()). @sinceJDK11.2
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()). @sinceClass Vector, void clear()JDK11.2
Removes all of the elements from this Vector. The Vector will be empty after this call returns (unless it throws an exception). @sinceClass Vector, void ensureCapacity(int)JDK11.2
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.Class Vector, Object get(int)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.
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()). @sinceClass Vector, int indexOf(Object, int)JDK11.2
Searches for the first occurence of the given argument beginning the search atClass Vector, int lastIndexOf(Object, int)index
and testing for equality using theequals
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 positionindex
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)
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 toClass Vector, boolean remove(Object)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.
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 thatClass Vector, Object remove(int)(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. @sinceJDK11.2
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. @sinceClass Vector, boolean removeAll(Collection)JDK11.2
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. @sinceClass Vector, void removeRange(int, int)JDK11.2
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. @paramClass Vector, boolean retainAll(Collection)fromIndextoIndex index after last element to be removed.
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. @sinceClass Vector, Object set(int, Object)JDK11.2
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. @sinceClass Vector, List subList(int, int)JDK11.2
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.Class Vector, Object[] toArray()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)
Returns an array containing all of the elements in this Vector in the correct order. @sinceClass Vector, int capacityIncrementJDK11.2
The amount by which the capacity of the vector is automatically incremented when its size becomes greater than its capacity. If the capacity increment is0less than or equal to zero the capacity of the vector is doubled each time it needs to grow. @serial
A hashtable-basedClass WeakHashMap, constructor WeakHashMap()Map
implementation with weak keys. An entry in aWeakHashMap
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 otherMap
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 theCollections.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 aWeakHashMap
at some later time and be surprised that its entry has been removed. This class will work perfectly well with key objects whoseequals
methods are not based upon object identity such asString
instances. With such recreatable key objects however the automatic removal ofWeakHashMap
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 aWeakHashMap
may behave as though an unknown thread is silently removing entries. In particular even if you synchronize on aWeakHashMap
instance and invoke none of its mutator methods it is possible for thesize
method to return smaller values over time for theisEmpty
method to returnfalse
and thentrue
for thecontainsKey
method to returntrue
and laterfalse
for a given key for theget
method to return a value for a given key but later returnnull
for theput
method to returnnull
and theremove
method to returnfalse
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 theWeakHashMap
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 @sinceJDK11.2 @see java.util.HashMap @see java.lang.ref.WeakReference
Constructs a new emptyWeakHashMap
with the default initial capacity and the default load factor which is0.75
.