|
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 addAll(Collection)To implement an unmodifiable collection the programmer needs only to extend this class and provide implementations for the iterator and size methods. (The iterator returned by the iterator method must implement hasNext and next.)
To implement a modifiable collection the programmer must additionally override this class's add method (which otherwise throws an UnsupportedOperationException) and the iterator returned by the iterator method must additionally implement its remove method.
The programmer should generally provide a void (no argument) and Collection constructor as per the recommendation in the Collection interface specification.
The documentation for each non-abstract methods in this class describes its implementation in detail. Each of these methods may be overridden if the collection being implemented admits a more efficient implementation. @author Josh Bloch @version 1.
16 0223 12/0203/0001 @see Collection @since 1.2
Adds all of the elements in the specified collection to this collection (optional operation). The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified collection is this collection and this collection is nonempty.)Class AbstractCollection, void clear()This implementation iterates over the specified collection and adds each object returned by the iterator to this collection in turn.
Note that this implementation will throw an UnsupportedOperationException unless add is overridden (assuming the specified collection is non-empty). @param c collection whose elements are to be added to this collection. @return true if this collection changed as a result of the call. @throws UnsupportedOperationException if this collection does not support the addAll method.
is@throwsnot supported by thisNullPointerException if the specified collection is null. @see #add(Object)
Removes all of the elements from this collection (optional operation). The collection will be empty after this call returns (unless it throws an exception).Class AbstractCollection, boolean containsAll(Collection)This implementation iterates over this collection removing each element using the Iterator.remove operation. Most implementations will probably choose to override this method for efficiency.
Note that this implementation will throw an UnsupportedOperationException if the iterator returned by this collection's iterator method does not implement the remove method and this collection is non-empty. @throws UnsupportedOperationException if the
removeclear method is not supported by this collection.
Returns true if this collection contains all of the elements in the specified collection.Class AbstractCollection, boolean remove(Object)This implementation iterates over the specified collection checking each element returned by the iterator in turn to see if it's contained in this collection. If all elements are so contained true is returned otherwise false. @param c collection to be checked for containment in this collection. @return true if this collection contains all of the elements in the specified collection. @throws NullPointerException if the specified collection is null. @see #contains(Object)
Removes a single instance of the specified element from this collection if it is present (optional operation). More formally removes an element e such that (o==null e==null : o.equals(e)) if the collection contains one or more such elements. Returns true if the collection contained the specified element (or equivalently if the collection changed as a result of the call).Class AbstractCollection, boolean removeAll(Collection)This implementation iterates over the collection looking for the specified element. If it finds the element it removes the element from the collection using the iterator's remove method.
Note that this implementation throws an UnsupportedOperationException if the iterator returned by this collection's iterator method does not implement the remove method and this collection contains the specified object. @param o element to be removed from this collection if present. @return true if the collection contained the specified element. @throws UnsupportedOperationException if the remove method is not supported by this collection.
Removes from this collection all of its elements that are contained in the specified collection (optional operation).Class AbstractCollection, boolean retainAll(Collection)This implementation iterates over this collection checking each element returned by the iterator in turn to see if it's contained in the specified collection. If it's so contained it's removed from this collection with the iterator's remove method.
Note that this implementation will throw an UnsupportedOperationException if the iterator returned by the iterator method does not implement the remove method and this collection contains one or more elements in common with the specified collection. @param c elements to be removed from this collection. @return true if this collection changed as a result of the call. @throws UnsupportedOperationException if the removeAll method is not supported by this collection. @throws NullPointerException if the specified collection is null. @see #remove(Object) @see #contains(Object)
Retains only the elements in this collection that are contained in the specified collection (optional operation). In other words removes from this collection all of its elements that are not contained in the specified collection.Class AbstractCollection, Object[] toArray(Object[])This implementation iterates over this collection checking each element returned by the iterator in turn to see if it's contained in the specified collection. If it's not so contained it's removed from this collection with the iterator's remove method.
Note that this implementation will throw an UnsupportedOperationException if the iterator returned by the iterator method does not implement the remove method and this collection contains one or more elements not present in the specified collection. @param c elements to be retained in this collection. @return true if this collection changed as a result of the call. @throws UnsupportedOperationException if the retainAll method is not supported by this Collection. @throws NullPointerException if the specified collection is null. @see #remove(Object) @see #contains(Object)
Returns an arraywith a runtime type iscontaining all of the elementsthatin this collection; the runtime type of thespecifiedreturned arrayandis thatcontains allof theelements in thisspecifiedcollectionarray. If the collection fits in the specified array it is returned therein. Otherwise a new array is allocated with the runtime type of the specified array and the size of this collection.If the collection fits in the specified array with room to spare (i.e. the array has more elements than the collection) the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the collection only if the caller knows that the collection does not contain any null elements.)
If this collection makes any guarantees as to what order its elements are returned by its iterator this method must return the elements in the same order.
This implementation checks if the array is large enough to contain the collection; if not it allocates a new array of the correct size and type (using reflection). Then it iterates over the collection storing each object reference in the next consecutive element of the array starting with element 0. If the array is larger than the collection a null is stored in the first location after the end of the collection. @param a the array into which the elements of the collection are to be stored if it is big enough; otherwise a new array of the same runtime type is allocated for this purpose. @return an array containing the elements of the collection. @throws NullPointerException if the specified array is null. @throws ArrayStoreException if the runtime type of the specified array is not a supertype of the runtime type of every element in this collection.
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array). For sequential access data (such as a linked list) AbstractSequentialList should be used in preference to this class.Class AbstractList, boolean addAll(int, Collection)To implement an unmodifiable list the programmer needs only to extend this class and provide implementations for the get(int index) and size() methods.
To implement a modifiable list the programmer must additionally override the set(int index Object element) method (which otherwise throws an UnsupportedOperationException. If the list is variable-size the programmer must additionally override the add(int index Object element) and remove(int index) methods.
The programmer should generally provide a void (no argument) and collection constructor as per the recommendation in the Collection interface specification.
Unlike the other abstract collection implementations the programmer does not have to provide an iterator implementation; the iterator and list iterator are implemented by this class on top the "random access" methods: get(int index) set(int index Object element) set(int index Object element) add(int index Object element) and remove(int index).
The documentation for each non-abstract methods in this class describes its implementation in detail. Each of these methods may be overridden if the collection being implemented admits a more efficient implementation. @author Josh Bloch @version 1.
31 0235 12/0203/0001 @see Collection @see List @see AbstractSequentialList @see AbstractCollection @since 1.2
Inserts all of the elements in the specified collection into this list at the specified position (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection's iterator. The behavior of this operation is unspecified if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list and it's nonempty.)Class AbstractList, List subList(int, int)This implementation gets an iterator over the specified collection and iterates over it inserting the elements obtained from the iterator into this list at the appropriate position one at a time using add(int Object). Many implementations will override this method for efficiency.
Note that this implementation throws an UnsupportedOperationException unless add(int Object) is overridden. @return true if this list changed as a result of the call. @param index index at which to insert the first element from the specified collection. @param c elements to be inserted into this List. @throws UnsupportedOperationException if the addAll method is not supported by this list. @throws ClassCastException if the class of an element of the specified collection prevents it from being added to this List. @throws IllegalArgumentException some aspect an element of the specified collection prevents it from being added to this List. @throws IndexOutOfBoundsException index out of range (index < 0 || index > size()). @throws NullPointerException if the specified collection is null.
Returns a view of the portion of this list between fromIndex inclusive and toIndex exclusive. (If fromIndex and toIndex are equal the returned list is empty.) The returned list is backed by this list so changes in the returned list are reflected in this list and vice-versa. The returned list supports all of the optional list operations supported by this list.This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by operating on a subList view instead of a whole list. For example the following idiom removes a range of elements from a list:
list.subList(from to).clear();Similar idioms may be constructed for indexOf and lastIndexOf and all of the algorithms in the Collections class can be applied to a subList.The semantics of the list returned by this method become undefined if the backing list (i.e. this list) is structurally modified in any way other than via the returned list. (Structural modifications are those that change the size of the list or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)
This implementation returns a list that subclasses AbstractList. The subclass stores in private fields the offset of the subList within the backing list the size of the subList (which can change over its lifetime) and the expected modCount value of the backing list. There are two variants of the subclass one of which implements RandomAccess. If this list implements RandomAccess the returned list will be an instance of the subclass that implements RandomAccess.
The subclass's set(int Object) get(int) add(int Object) remove(int) addAll(int Collection) and removeRange(int int) methods all delegate to the corresponding methods on the backing abstract list after bounds-checking the index and adjusting for the offset. The addAll(Collection c) method merely returns addAll(size c).
The listIterator(int) method returns a "wrapper object" over a list iterator on the backing list which is created with the corresponding method on the backing list. The iterator method merely returns listIterator() and the size method merely returns the subclass's size field.
All methods first check to see if the actual modCount of the backing list is equal to its expected value and throw a ConcurrentModificationException if it is not. @param fromIndex low endpoint (inclusive) of the subList. @param toIndex high endpoint (exclusive) of the subList. @return a view of the specified range within this list. @throws IndexOutOfBoundsException endpoint index value out of range (fromIndex < 0 || toIndex > size) @throws IllegalArgumentException endpoint indices out of order (fromIndex > toIndex)
This class provides a skeletal implementation of the Map interface to minimize the effort required to implement this interface.Class AbstractMap, void clear()To implement an unmodifiable map the programmer needs only to extend this class and provide an implementation for the entrySet method which returns a set-view of the map's mappings. Typically the returned set will in turn be implemented atop AbstractSet. This set should not support the add or remove methods and its iterator should not support the remove method.
To implement a modifiable map the programmer must additionally override this class's put method (which otherwise throws an UnsupportedOperationException) and the iterator returned by entrySet().iterator() must additionally implement its remove method.
The programmer should generally provide a void (no argument) and map constructor as per the recommendation in the Map interface specification.
The documentation for each non-abstract methods in this class describes its implementation in detail. Each of these methods may be overridden if the map being implemented admits a more efficient implementation. @author Josh Bloch @version 1.
21 0232 12/0203/0001 @see Map @see Collection @since 1.2
Removes all mappings from this map (optional operation).Class AbstractMap, Object clone()This implementation calls entrySet().clear(). Note that this implementation throws an UnsupportedOperationException if the entrySet does not support the clear operation. @throws UnsupportedOperationException clear is not supported by this map.
Class AbstractMap, boolean containsKey(Object)CreatesReturnsand returnsacopy of this object. The precise meaning ofshallow"copy" may depend on the class of the object. The general intent is that for any object x the expression: x.clone() = x will be true and that the expression: x.clone().getClass() == x.getClass() will be true but these are not absolute requirements. While it is typically the case that: x.clone().equals(x) will be true this is not an absolute requirement. Copyingan object will typically entail creating a new instance of its class but it also may require copying of internal data structures as well. No constructors are called. The method clone for class Object performs a specific cloning operation. First if the classof thisobject does not implement the interface Cloneable then aCloneNotSupportedExceptionAbstractMapis thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise this method creates a newinstanceof: theclass of this objectkeys andinitializes all its fields withvaluesexactly the contents of the corresponding fields of this object as if by assignment; the contents of the fieldsthemselves are notthemselvescloned.Thus this method performs@return a"shallow copy" of this object not a "deep copy" operation. The class Object does not itself implement the interface Cloneable so calling the clone method on an object whose class is Object will result in throwing an exception at run time. The clone method is implemented by the class Object as aconvenient general utility for subclasses that implement the interface Cloneable possibly also overriding the clone method in which case the overriding definition can refer to this utility definition by the call: super.clone() @return a cloneof thisinstance. @exception CloneNotSupportedException if the object's class does not support the Cloneable interface. Subclasses that override the clone method can also throw this exception to indicate that an instance cannot be cloned. @exception OutOfMemoryError if there is not enough memory. @see java.langmap.Cloneable
Returns true if this map contains a mapping for the specified key.Class AbstractMap, Object get(Object)This implementation iterates over entrySet() searching for an entry with the specified key. If such an entry is found true is returned. If the iteration terminates without finding such an entry false is returned. Note that this implementation requires linear time in the size of the map; many implementations will override this method. @param key key whose presence in this map is to be tested. @return true if this map contains a mapping for the specified key. @throws
ClassCastException if the specified key is of an inappropriate type for this map. @throwsNullPointerException key is null and this map does not not permit null keys.
Returns the value to which this map maps the specified key. Returns null if the map contains no mapping for this key. A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.Class AbstractMap, void putAll(Map)This implementation iterates over entrySet() searching for an entry with the specified key. If such an entry is found the entry's value is returned. If the iteration terminates without finding such an entry null is returned. Note that this implementation requires linear time in the size of the map; many implementations will override this method. @param key key whose associated value is to be returned. @return the value to which this map maps the specified key. @throws
ClassCastException if the specified key is of an inappropriate type for this map. @throwsNullPointerException if the key is null and this map does not not permit null keys. @see #containsKey(Object)
Copies all of the mappings from the specified map to this map (optional operation). These mappings will replace any mappings that this map had for any of the keys currently in the specified map.Class AbstractMap, Object remove(Object)This implementation iterates over the specified map's entrySet() collection and calls this map's put operation once for each entry returned by the iteration.
Note that this implementation throws an UnsupportedOperationException if this map does not support the put operation and the specified map is nonempty. @param t mappings to be stored in this map. @throws UnsupportedOperationException if the putAll operation is not supported by this map. @throws ClassCastException if the class of a key or value in the specified map prevents it from being stored in this map. @throws IllegalArgumentException if some aspect of a key or value in the specified map prevents it from being stored in this map. @throws NullPointerException the specified map is null or if this map does not permit null keys or values and the specified
key or valuemapiscontains null keys or values.
Removes the mapping for this key from this map if present (optional operation).This implementation iterates over entrySet() searching for an entry with the specified key. If such an entry is found its value is obtained with its getValue operation the entry is is removed from the Collection (and the backing map) with the iterator's remove operation and the saved value is returned. If the iteration terminates without finding such an entry null is returned. Note that this implementation requires linear time in the size of the map; many implementations will override this method.
Note that this implementation throws an UnsupportedOperationException if the entrySet iterator does not support the remove method and this map contains a mapping for the specified key. @param key key whose mapping is to be removed from the map. @return previous value associated with specified key or null if there was no entry for key. (A null return can also indicate that the map previously associated null with the specified key if the implementation supports null values.) @throws UnsupportedOperationException if the remove operation is not supported by this map.
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "sequential access" data store (such as a linked list). For random access data (such as an array) AbstractList should be used in preference to this class.Class AbstractSequentialList, boolean addAll(int, Collection)This class is the opposite of the AbstractList class in the sense that it implements the "random access" methods (get(int index) set(int index Object element) set(int index Object element) add(int index Object element) and remove(int index)) on top of the list's list iterator instead of the other way around.
To implement a list the programmer needs only to extend this class and provide implementations for the listIterator and size methods. For an unmodifiable list the programmer need only implement the list iterator's hasNext next hasPrevious previous and index methods.
For a modifiable list the programmer should additionally implement the list iterator's set method. For a variable-size list the programmer should additionally implement the list iterator's remove and add methods.
The programmer should generally provide a void (no argument) and collection constructor as per the recommendation in the Collection interface specification. @author Josh Bloch @version 1.
21 0225 12/0203/0001 @see Collection @see List @see AbstractList @see AbstractCollection @since 1.2
Inserts all of the elements in in the specified collection into this list at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection's iterator. The behavior of this operation is unspecified if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list and it's nonempty.) Optional operation.Class AbstractSequentialList, Object get(int)This implementation gets an iterator over the specified collection and a list iterator over this list pointing to the indexed element (with listIterator(index)). Then it iterates over the specified collection inserting the elements obtained from the iterator into this list one at a time using ListIterator.add followed by ListIterator.next (to skip over the added element).
Note that this implementation will throw an UnsupportedOperationException if the list iterator returned by the listIterator method does not implement the add operation. @return true if this list changed as a result of the call. @param index index at which to insert first element from the specified collection. @param c elements to be inserted into this list. @throws UnsupportedOperationException if the addAll operation is not supported by this list. @throws NullPointerException this list does not permit null elements and one of the elements of the specified collection is null. @throws ClassCastException if the class of the specified element prevents it from being added to this list. @throws IllegalArgumentException if some aspect of the specified element prevents it from being added to this list. @throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()). @throws NullPointerException if the specified collection is null.
Returns the element at the specified position in this list.Class AbstractSequentialList, ListIterator listIterator(int)This implementation first gets a list iterator pointing to the indexed element (with listIterator(index)). Then it gets the element using ListIterator.next and returns it. @param index index of element to return. @return the element at the specified position in this list.
* @param index index of element to return. *@throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).
Returns a list iterator over the elements in this list (in proper sequence). @param index index of first element to be returned from the list iterator (by a call to the next
method) @return a list iterator over the elements in this list (in proper sequence).
This class provides a skeletal implementation of the Set interface to minimize the effort required to implement this interface.Class AbstractSet, boolean removeAll(Collection)The process of implementing a set by extending this class is identical to that of implementing a Collection by extending AbstractCollection except that all of the methods and constructors in subclasses of this class must obey the additional constraints imposed by the Set interface (for instance the add method must not permit addition of multiple intances of an object to a set).
Note that this class does not override any of the implementations from the AbstractCollection class. It merely adds implementations for equals and hashCode. @author Josh Bloch @version 1.
14 0217 12/0203/0001 @see Collection @see AbstractCollection @see Set @since 1.2
Removes from this set all of its elements that are contained in the specified collection (optional operation).This implementation determines which is the smaller of this set and the specified collection by invoking the size method on each. If this set has fewer elements then the implementation iterates over this set checking each element returned by the iterator in turn to see if it is contained in the specified collection. If it is so contained it is removed from this set with the iterator's remove method. If the specified collection has fewer elements then the implementation iterates over the specified collection removing from this set each element returned by the iterator using this set's remove method.
Note that this implementation will throw an UnsupportedOperationException if the iterator returned by the iterator method does not implement the remove method. @param c elements to be removed from this set. @return true if this set changed as a result of the call. @throws UnsupportedOperationException removeAll is not supported by this set. @throws NullPointerException if the specified collection is null. @see #remove(Object) @see #contains(Object)
Resizable-array implementation of the List interface. Implements all optional list operations and permits all elements including null. In addition to implementing the List interface this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector except that it is unsynchronized.)Class ArrayList, constructor ArrayList()The size isEmpty get set iterator and listIterator operations run in constant time. The add operation runs in amortized constant time that is adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added an ArrayList its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently and at least one of the threads modifies the list structurally it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time to prevent accidental unsynchronized access to the list:
List list = Collections.synchronizedList(new ArrayList(...));The iterators returned by this class's iterator and listIterator methods are fail-fast: if list is structurally modified at any time after the iterator is created in any way except through the iterator's own remove or add methods the iterator will throw a ConcurrentModificationException. Thus in the face of concurrent modification the iterator fails quickly and cleanly rather than risking arbitrary non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. @author Josh Bloch @version 1.
25 0236 12/0203/0001 @see Collection @see List @see LinkedList @see Vector @see Collections#synchronizedList(List) @since 1.2
Constructs an empty list with an initial capacity of ten.Class ArrayList, constructor ArrayList(Collection)
Constructs a list containing the elements of the specified collection in the order they are returned by the collection's iterator. The ArrayList instance has an initial capacity of 110% the size of the specified collection. @param c the collection whose elements are to be placed into this list. @throws NullPointerException if the specified collection is null.Class ArrayList, boolean addAll(Collection)
Appends all of the elements in the specified Collection to the end of this list in the order that they are returned by the specified Collection's Iterator. The behavior of this operation is undefined if the specified Collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified Collection is this list and this list is nonempty.) @param c the elements to be inserted into this list. @return true if this list changed as a result of the call. @throws IndexOutOfBoundsException if index out of range (index < 0 || index > size()). @throws NullPointerException if the specified collection is null.Class ArrayList, boolean addAll(int, Collection)
Inserts all of the elements in the specified Collection into this list starting at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified Collection's iterator. @param index index at which to insert first element from the specified collection. @param c elements to be inserted into this list. @return true if this list changed as a result of the call. @throws IndexOutOfBoundsException if index out of range (index < 0 || index > size()). @throws NullPointerException if the specified Collection is null.Class ArrayList, boolean contains(Object)
Returns true if this list contains the specified element. @param elem element whose presence in this List is to be tested. @returnClass ArrayList, Object[] toArray(Object[])true
if the specified element is present;false
otherwise.
Returns an array containing all of the elements in this list in the correct order. The; the runtime type of the returned array is that of the specified array. If the list fits in the specified array it is returned therein. Otherwise a new array is allocated with the runtime type of the specified array and the size of this list.If the list fits in the specified array with room to spare (i.e. the array has more elements than the list) the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements. @param a the array into which the elements of the list are to be stored if it is big enough; otherwise a new array of the same runtime type is allocated for this purpose. @return an array containing the elements of the list. @throws ArrayStoreException if the runtime type of a is not a supertype of the runtime type of every element in this list.
This class contains various methods for manipulating arrays (such as sorting and searching).Class Arrays, List asList(Object[])ItThis class also contains a static factory that allows arrays to be viewed as lists.The
documentationmethodsforin this class all throw a NullPointerException if thesorting andspecified arraysearchingreference is null.The documentation for the
methods contained in this class includes briefs description of the implementations. Such descriptions should be regarded as implementation notes rather than parts of the specification. Implementors should feel free to substitute other algorithms so long as the specification itself is adhered to. (For example the algorithm used by sort(Object[]) does not have to be a mergesort but it does have to be stable.) @author Josh Bloch @version 1.37 0244 12/0203/0001 @see Comparable @see Comparator @since 1.2
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs in combination with Collection.toArray. The returned list is serializableClass Arrays, int binarySearch(Object[], Object).and implements RandomAccess @param a the array by which the list will be backed. @return a list view of the specified array. @see Collection#toArray()
Searches the specified array for the specified object using the binary search algorithm. The array must be sorted into ascending order according to the natural ordering of its elements (as by Sort(Object[]) above) prior to making this call. If it is not sorted the results are undefined. (If the array contains elements that are not mutually comparable (for example strings and integers) it cannot be sorted according to the natural order of its elements hence results are undefined.) If the array contains multiple elements equal to the specified object there is no guarantee which one will be found. @param a the array to be searched. @param key the value to be searched for. @return index of the search key if it is contained in the list; otherwise (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. @throws ClassCastException if theClass Arrays, int binarySearch(double[], double)array contains elements that are not mutually comparable (for example strings and integers) or thesearch key in notmutuallycomparablewithto the elements of the array. @see Comparable @see #sort(Object[])
Searches the specified array of doubles for the specified value using the binary search algorithm. The array must be sorted (as by the sort method above) prior to making this call. If it is not sorted the results are undefined. If the array contains multiple elements with the specified value there is no guarantee which one will be found. This method considers all NaN values to be equivalent and equal. @param a the array to be searched. @param key the value to be searched for. @return index of the search key if it is contained in the list; otherwise (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. @see #sort(double[])Class Arrays, int binarySearch(float[], float)
Searches the specified array of floats for the specified value using the binary search algorithm. The array must be sorted (as by the sort method above) prior to making this call. If it is not sorted the results are undefined. If the array contains multiple elements with the specified value there is no guarantee which one will be found. This method considers all NaN values to be equivalent and equal. @param a the array to be searched. @param key the value to be searched for. @return index of the search key if it is contained in the list; otherwise (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. @see #sort(float[])Class Arrays, boolean equals(boolean[], boolean[])
Returns true if the two specified arrays ofClass Arrays, void sort(double[])equalsbooleans are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements and all corresponding pairs of elements in the two arrays are equal. In other words two arrays are equal if they contain the same elements in the same order. Also two array references are considered equal if both are null.@param a one array to be tested for equality. @param a2 the other array to be tested for equality. @return true if the two arrays are equal.
Sorts the specified array of doubles into ascending numerical order.Class Arrays, void sort(double[], int, int)The
<
relation does not provide a total order on all floating-point values; although they are distinct numbers-0.0 == 0.0
istrue
and a NaN value compares neither less than greater than nor equal to any floating-point value even itself. To allow the sort to proceed instead of using the<
relation to determine ascending numerical order this method uses the total order imposed by Double#compareTo This ordering differs from the<
relation in that-0.0
is treated as less than0.0
and NaN is considered greater than any other floating-point value. For the purposes of sorting all NaN values are considered equivalent and equal.The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted.
Sorts the specified range of the specified array of doubles into ascending numerical order. The range to be sorted extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be sorted is empty.)Class Arrays, void sort(float[])The
<
relation does not provide a total order on all floating-point values; although they are distinct numbers-0.0 == 0.0
istrue
and a NaN value compares neither less than greater than nor equal to any floating-point value even itself. To allow the sort to proceed instead of using the<
relation to determine ascending numerical order this method uses the total order imposed by Double#compareTo This ordering differs from the<
relation in that-0.0
is treated as less than0.0
and NaN is considered greater than any other floating-point value. For the purposes of sorting all NaN values are considered equivalent and equal.The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
Sorts the specified array of floats into ascending numerical order.Class Arrays, void sort(float[], int, int)The
<
relation does not provide a total order on all floating-point values; although they are distinct numbers-0.0f == 0.0f
istrue
and a NaN value compares neither less than greater than nor equal to any floating-point value even itself. To allow the sort to proceed instead of using the<
relation to determine ascending numerical order this method uses the total order imposed by Float#compareTo This ordering differs from the<
relation in that-0.0f
is treated as less than0.0f
and NaN is considered greater than any other floating-point value. For the purposes of sorting all NaN values are considered equivalent and equal.The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted.
Sorts the specified range of the specified array of floats into ascending numerical order. The range to be sorted extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be sorted is empty.)The
<
relation does not provide a total order on all floating-point values; although they are distinct numbers-0.0f == 0.0f
istrue
and a NaN value compares neither less than greater than nor equal to any floating-point value even itself. To allow the sort to proceed instead of using the<
relation to determine ascending numerical order this method uses the total order imposed by Float#compareTo This ordering differs from the<
relation in that-0.0f
is treated as less than0.0f
and NaN is considered greater than any other floating-point value. For the purposes of sorting all NaN values are considered equivalent and equal.The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function" Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length
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.
Unless otherwise noted passing a null parameter to any of the methods in a
BitSet
will result in aNullPointerException
. ABitSet
is not safe for multithreaded use without external synchronization. @author Arthur van Hoff @author Michael McCloskey @version 1.46 0254 12/0203/0001 @since JDK1.0
Clears all of the bits in thisClass BitSet, int hashCode()BitSet
whose corresponding bit is set in the specifiedBitSet
. @param set theBitSet
with which to mask thisBitSet
. @since1JDK1.2
Returns a hash code value for this bit set. The has code depends only on which bits have been set within thisClass BitSet, void set(int)BitSet
. The algorithm used to compute it may be described as follows.Suppose the bits in the
BitSet
were to be stored in an array oflong
integers called saybits
in such a manner that bitk
is set in theBitSet
(for nonnegative values ofk
) if and only if the expression((k>>6) < bits.length) && ((bits[k>>6] & (1L << (bit & 0x3F))) = 0)is true. Then the following definition of thehashCode
method would be a correct implementation of the actual algorithm:publicNote that the hash code values change if the set of bits is altered.synchronizedint hashCode() { long h = 1234; for (int i = bits.length; --i >= 0; ) { h ^= bits[i] * (i + 1); } return (int)((h >> 32) ^ h); }Overrides the
hashCode
method ofObject
. @return a hash code value for this bit set.
Sets the bitClass BitSet, String toString()specified byat the specified index totrue
. @param bitIndex a bit index. @exception IndexOutOfBoundsException if the specified index is negative. @since JDK1.0
Returns a string representation of this bit set. For every index for which thisBitSet
contains a bit in the set state the decimal representation of that index is included in the result. Suchindeces aerindices are listed in order from lowest to highest separated by "$ " (a comma and a space) and surrounded by braces resulting in the usual mathematical notation for a set of integers.Overrides the
toString
method ofObject
.Example:
BitSet drPepper = new BitSet();NowdrPepper.toString()
returns "{}
".
drPepper.set(2);NowdrPepper.toString()
returns "{2}
".
drPepper.set(4); drPepper.set(10);NowdrPepper.toString()
returns "{2 4 10}
". @return a string representation of this bit set.
Class Calendar, int get(int)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. The platform provides one concrete subclass ofCalendar
:GregorianCalendar
. Future subclasses could represent the various types of lunar calendars in use in many parts of the world.Like other locale-sensitive classes
Calendar
provides a class methodgetInstance
for getting a generally useful object of this type.Calendar
'sgetInstance
method returns aobject whose time fields have been initialized with the current date and time:
GregorianCalendarCalendarCalendar rightNow = Calendar.getInstance();A
Calendar
object can produce all the time field values needed to implement the date-time formatting for a particular language and calendar style (for example Japanese-Gregorian Japanese-Traditional).Calendar
defines the range of values returned by certain fields as well as their meaning. For example the first month of the year has 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
historialhistorical Arabic astronomical calendar requires year month day-of-month and day-of-week in some cases.Note: There are certain possible ambiguities in interpretation of certain singular times which are resolved in the following ways:
2423:59 is the last minute of the day and 00:00"belongs"istothe first minute of thefollowingnext day.That isThus 23:59 on Dec 3119691999 <2400:00 on Jan 119702000 <2400:01:00on Jan 119702000.- Although historically not precise midnight also belongs to "am" and noon belongs to "pm" so on the same day 12:00 am (midnight) < 12:01 am and 12:00 pm (noon) < 12:01 pm
The date or time format strings are not part of the definition of a calendar as those must be modifiable or overridable by the user at runtime. Use DateFormat to format dates.
Field manipulation methods
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. Calling roll(Calendar.MONTH 8) sets the calendar to April 30 1999. Add rule 1 sets the MONTH field to April. Using a GregorianCalendar the DAY_OF_MONTH cannot be 31 in the month April. Add rule 2 sets it to the closest possible value 30. Finally the roll rule maintains the YEAR field value of 1999. Example: Consider a GregorianCalendar originally set to Sunday June 6 1999. Calling roll(Calendar.WEEK_OF_MONTH -1) sets the calendar to Tuesday June 1 1999 whereas calling add(Calendar.WEEK_OF_MONTH -1) sets the calendar to Sunday May 30 1999. This is because the roll rule imposes an additional constraint: The MONTH must not change when the WEEK_OF_MONTH is rolled. Taken together with add rule 1 the resultant date must be between Tuesday June 1 and Saturday June 5. According to add rule 2 the DAY_OF_WEEK an invariant when changing the WEEK_OF_MONTH is set to Tuesday the closest possible value to Sunday (where Sunday is the first day of theSeeweekint).Usage model. To motivate the behavior of
@see Date @see GregorianCalendar @see TimeZone @see java.text.DateFormat @version 1.add()
androll()
consider a user interface component with increment and decrement buttons for the month day and year and an underlyingGregorianCalendar
. If the interface reads January 31 1999 and the user presses the month increment button what should it read If the underlying implementation usesset()
it might read March 3 1999. A better result would be February 28 1999. Furthermore if the user presses the month increment button again it should read March 31 1999 not March 28 1999. By saving the original date and using eitheradd()
orroll()
depending on whether larger fields should be affected the user interface can behave as most users will intuitively expect.49 0169 12/1903/0001 @author Mark Davis David Goldsmith Chen-Lieh Huang Alan Liu @since JDK1.1
Gets the value for a given time field. @param field the given time field. @return the value for the given time field. @throws ArrayIndexOutOfBoundsException if specified field is out of range (field < 0 || field >= FIELD_COUNT).Class Calendar, Calendar getInstance()
Gets a calendar using the default time zone and locale. The Calendar
returned is based on the current time in the default time zone with the default locale. @return a Calendar.
Class Calendar, Calendar getInstance(Locale)Gets a calendar using the default time zone and specified locale. The Calendar
returned is based on the current time in the default time zone with the given locale. @param aLocale the locale for the week data @return a Calendar.
Class Calendar, Calendar getInstance(TimeZone)Gets a calendar using the specified time zone and default locale. The Calendar
returned is based on the current time in the given time zone with the default locale. @param zone the time zone to use @return a Calendar.
Class Calendar, Calendar getInstance(TimeZone, Locale)Gets a calendar with the specified time zone and locale. The Calendar
returned is based on the current time in the given time zone with the given locale. @param zone the time zone to use @param aLocale the locale for the week data @return a Calendar.
Class Calendar, Date getTime()Gets this Calendar's current time. @return the current time. @see #setTime @see #getTimeInMillisClass Calendar, long getTimeInMillis()
Gets this Calendar's current time as a long. @return the current time as UTC milliseconds from the epoch. @see #getTime @see #setTimeInMillisClass Calendar, void roll(int, boolean)
Time Field Rolling function.Class Calendar, void roll(int, int)RollsAdds or subtracts (up/down) a single unit of time on the given time field without changing larger fields. For example to roll the current date up by one day you can achieve it by calling:roll(Calendar.DATE true). When rolling on the year or Calendar.YEAR field it will roll the year value in the range between 1 and the value returned by calling getMaximum(Calendar.YEAR). When rolling on the month or Calendar.MONTH field other fields like date might conflict and need to be changed. For instance rolling the month on the date 01/31/96 will result in 02/29/96. When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field it will roll the hour value in the range between 0 and 23 which is zero-based. @param field the time field. @param up indicates if the value of the specified time field is to be rolled up or rolled down. Use true if rolling up false otherwise. @see Calendar#add @see Calendar#set
Time Field Rolling function.Class Calendar, void set(int, int)RollsAddup or down the specifiedtonumber of units on the given time fieldfield a signed amount without changing larger fields.(A negative roll amount means to roll down.)[NOTE: This default implementation on Calendar just repeatedly calls the version of roll() that takes a boolean and rolls by one unit. This may not always do the right thing. For example if the DAY_OF_MONTH field is 31 rolling through February will leave it set to 28. The GregorianCalendar version of this function takes care of this problem. Other subclasses should also provide overrides of this function that do the right thing. @param field the time field. @param amount the signed amount to add tofield
. @since 1.2 @see Calendar#add @see Calendar#set
Sets the time field with the given value. @param field the given time field. @param value the value to be set for the given time field. @throws ArrayIndexOutOfBoundsException if specified field is out of range (field < 0 || field >= FIELD_COUNT).Class Calendar, void setTime(Date)
Sets this Calendar's current time with the given Date.Class Calendar, void setTimeInMillis(long)Note: Calling
setTime()
withDate(Long.MAX_VALUE)
orDate(Long.MIN_VALUE)
may yield incorrect field values fromget()
. @param date the given Date. @see #getTime @see #setTimeInMillis
Sets this Calendar's current time from the given long value. @paramClass Calendar, int DAY_OF_WEEK_IN_MONTHdatemillis the new time in UTC milliseconds from the epoch. @see #setTime @see #getTimeInMillis
Field number forClass Calendar, int DST_OFFSETget
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. 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
throughcorrespond to
1514DAY_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 Sunday of a month is specified asDAY_OF_WEEK = SUNDAY DAY_OF_WEEK_IN_MONTH = -1
. Because negative values count backward they will usually be aligned differently within the month than positive values. For example if a month has 31 daysDAY_OF_WEEK_IN_MONTH -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 FIELD_COUNTget
andset
indicating the daylight savings offset in milliseconds.This field reflects the correct daylight saving offset value of the time zone of this
Calendar
if theTimeZone
implementation subclass supports historical Daylight Saving Time schedule changes.
The number ofClass Calendar, int MONTHdistictdistinct fields recognized byget
andset
. Field numbers range from0..FIELD_COUNT-1
.
Field number forClass Calendar, int ZONE_OFFSETget
andset
indicating the month. This is a calendar-specific value. The first month of the year isJANUARY
which is 0; the last depends on the number of months in a year. @see #JANUARY @see #FEBRUARY @see #MARCH @see #APRIL @see #MAY @see #JUNE @see #JULY @see #AUGUST @see #SEPTEMBER @see #OCTOBER @see #NOVEMBER @see #DECEMBER @see #UNDECIMBER
Field number forget
andset
indicating the raw offset from GMT in milliseconds.This field reflects the correct GMT offset value of the time zone of this
Calendar
if theTimeZone
implementation subclass supports historical GMT offset changes.
The root interface in the collection hierarchy. A collection represents a group of objects known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The SDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.Class Collection, boolean add(Object)Bags or multisets (unordered collections that may contain duplicate elements) should implement this interface directly.
All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor which creates an empty collection and a constructor with a single argument of type Collection which creates a new collection with the same elements as its argument. In effect the latter constructor allows the user to copy any collection producing an equivalent collection of the desired implementation type. There is no way to enforce this convention (as interfaces cannot contain constructors) but all of the general-purpose Collection implementations in the
SDKJava platform libraries comply.The "destructive" methods contained in this interface that is the methods that modify the collection on which they operate are specified to throw UnsupportedOperationException if this collection does not support the operation. If this is the case these methods may but are not required to throw an UnsupportedOperationException if the invocation would have no effect on the collection. For example invoking the #addAll(Collection) method on an unmodifiable collection may but is not required to throw the exception if the collection to be added is empty.
Some collection implementations have restrictions on the elements that they may contain. For example some implementations prohibit null elements and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the collection may throw an exception or it may succeed at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface. @author Josh Bloch @version 1.
3132 02/0223/00 @see Set @see List @see Map @see SortedSet @see SortedMap @see HashSet @see TreeSet @see ArrayList @see LinkedList @see Vector @see Collections @see Arrays @see AbstractCollection @since 1.2
Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.)Class Collection, boolean addAll(Collection)Collections that support this operation may place limitations on what elements may be added to this collection. In particular some collections will refuse to add null elements and others will impose restrictions on the type of elements that may be added. Collection classes should clearly specify in their documentation any restrictions on what elements may be added.
If a collection refuses to add a particular element for any reason other than that it already contains the element it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns. @param o element whose presence in this collection is to be ensured. @return true if this collection changed as a result of the call @throws UnsupportedOperationException add is not supported by this collection. @throws ClassCastException class of the specified element prevents it from being added to this collection. @throws NullPointerException if the specified element is null and this collection does not support null elements. @throws IllegalArgumentException some aspect of this element prevents it from being added to this collection.
Adds all of the elements in the specified collection to this collection (optional operation). The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified collection is this collection and this collection is nonempty.) @param c elements to be inserted into this collection. @return true if this collection changed as a result of the call @throws UnsupportedOperationException if this collection does not support the addAll method. @throws ClassCastException if the class of an element of the specified collection prevents it from being added to this collection. @throws NullPointerException if the specified collection contains one or more null elements and this collection does not support null elements or if the specified collection is null. @throws IllegalArgumentException some aspect of an element of the specified collection prevents it from being added to this collection. @see #add(Object)Class Collection, boolean contains(Object)
Returns true if this collection contains the specified element. More formally returns true if and only if this collection contains at least one element e such that (o==null e==null : o.equals(e)). @param o element whose presence in this collection is to be tested. @return true if this collection contains the specified element @throws ClassCastException if the type of the specified element is incompatible with this collection (optional). @throws NullPointerException if the specified element is null and this collection does not support null elements (optional).Class Collection, boolean containsAll(Collection)
Returns true if this collection contains all of the elements in the specified collection. @param c collection to be checked for containment in this collection. @return true if this collection contains all of the elements in the specified collection @throws ClassCastException if the types of one or more elements in the specified collection are incompatible with this collection (optional). @throws NullPointerException if the specified collection contains one or more null elements and this collection does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #contains(Object)Class Collection, boolean remove(Object)
Removes a single instance of the specified element from this collection if it is present (optional operation). More formally removes an element e such that (o==null e==null : o.equals(e)) if this collection contains one or more such elements. Returns true if this collection contained the specified element (or equivalently if this collection changed as a result of the call). @param o element to be removed from this collection if present. @return true if this collection changed as a result of the call @throws ClassCastException if the type of the specified element is incompatible with this collection (optional). @throws NullPointerException if the specified element is null and this collection does not support null elements (optional). @throws UnsupportedOperationException remove is not supported by this collection.Class Collection, boolean removeAll(Collection)
Removes all this collection's elements that are also contained in the specified collection (optional operation). After this call returns this collection will contain no elements in common with the specified collection. @param c elements to be removed from this collection. @return true if this collection changed as a result of the call @throws UnsupportedOperationException if the removeAll method is not supported by this collection. @throws ClassCastException if the types of one or more elements in this collection are incompatible with the specified collection (optional). @throws NullPointerException if this collection contains one or more null elements and the specified collection does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #remove(Object) @see #contains(Object)Class Collection, boolean retainAll(Collection)
Retains only the elements in this collection that are contained in the specified collection (optional operation). In other words removes from this collection all of its elements that are not contained in the specified collection. @param c elements to be retained in this collection. @return true if this collection changed as a result of the call @throws UnsupportedOperationException if the retainAll method is not supported by this Collection. @throws ClassCastException if the types of one or more elements in this collection are incompatible with the specified collection (optional). @throws NullPointerException if this collection contains one or more null elements and the specified collection does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #remove(Object) @see #contains(Object)Class Collection, Object[] toArray(Object[])
Returns an array containing all of the elements in this collection;whosethe runtime type of the returned array is that of the specified array. If the collection fits in the specified array it is returned therein. Otherwise a new array is allocated with the runtime type of the specified array and the size of this collection.If this collection fits in the specified array with room to spare (i.e. the array has more elements than this collection) the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of this collection only if the caller knows that this collection does not contain any null elements.)
If this collection makes any guarantees as to what order its elements are returned by its iterator this method must return the elements in the same order.
Like the toArray method this method acts as bridge between array-based and collection-based APIs. Further this method allows precise control over the runtime type of the output array and may under certain circumstances be used to save allocation costs
Suppose l is a List known to contain only strings. The following code can be used to dump the list into a newly allocated array of String:
String[] x = (String[]) v.toArray(new String[0]);Note that toArray(new Object[0]) is identical in function to toArray(). @param a the array into which the elements of this collection are to be stored if it is big enough; otherwise a new array of the same runtime type is allocated for this purpose. @return an array containing the elements of this collection @throws ArrayStoreException the runtime type of the specified array is not a supertype of the runtime type of every element in this collection. @throws NullPointerException if the specified array is null.
This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections "wrappers" which return a new collection backed by a specified collection and a few other odds and ends.Class Collections, int binarySearch(List, Object)The methods of this class all throw a NullPointerException if the collections provided to them are null. The documentation for the polymorphic algorithms contained in this class generally includes a brief description of the implementation. Such descriptions should be regarded as implementation notes rather than parts of the specification. Implementors should feel free to substitute other algorithms so long as the specification itself is adhered to. (For example the algorithm used by sort does not have to be a mergesort but it does have to be stable.)
The "destructive" algorithms contained in this class that is the algorithms that modify the collection on which they operate are specified to throw UnsupportedOperationException if the collection does not support the appropriate mutation primitive(s) such as the set method. These algorithms may but are not required to throw this exception if an invocation would have no effect on the collection. For example invoking the sort method on an unmodifiable list that is already sorted may or may not throw UnsupportedOperationException. @author Josh Bloch @version 1.
46 0459 12/0603/0001 @see Collection @see Set @see List @see Map @since 1.2
Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method above) prior to making this call. If it is not sorted the results are undefined. If the list contains multiple elements equal to the specified object there is no guarantee which one will be found.Class Collections, int binarySearch(List, Object, Comparator)This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access).
It may run in n log(n) time if it is called on aIf"sequentialtheaccess"specified list(which provides linear-time positionaldoesaccess).notIfimplement thespecified list implementsRandomAccesstheandAbstracSequentialListisinterfacelarge this method will doa sequential search instead ofanaiterator-based binary search; this offers linear performanceinstead ofthatn logperforms O(n)performance if this methodlinkis calledtraversals andonO(logan)LinkedListelementobjectcomparisons. @param list the list to be searched. @param key the key to be searched for. @return index of the search key if it is contained in the list; otherwise (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. @throws ClassCastException if the list contains elements that are not mutually comparable (for example strings and integers) or the search key in not mutually comparable with the elements of the list. @see Comparable @see #sort(List)
Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the specified comparator (as by the Sort(List Comparator) method above) prior to making this call. If it is not sorted the results are undefined. If the list contains multiple elements equal to the specified object there is no guarantee which one will be found.Class Collections, Enumeration enumeration(Collection)This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access).
It may run in n log(n) time if it is called on aIf"sequentialtheaccess"specified list(which provides linear-time positionaldoesaccess).notIfimplement thespecified listRandomAccessimplements theand isAbstracSequentialListlargeinterfacethis this method will doa sequential search instead ofanaiterator-based binary search; this offers linear performanceinstead ofthatn logperforms O(n)performance if this methodlinkis calledtraversals andonO(logan)LinkedListelementobjectcomparisons. @param list the list to be searched. @param key the key to be searched for. @param c the comparator by which the list is ordered. A null value indicates that the elements' natural ordering should be used. @return index of the search key if it is contained in the list; otherwise (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. @throws ClassCastException if the list contains elements that are not mutually comparable using the specified comparator or the search key in not mutually comparable with the elements of the list using this comparator. @see Comparable @see #sort(List Comparator)
Returns an enumeration over the specified collection. This provides interoperatbility with legacy APIs that require an enumeration as input. @param c the collection for which an enumeration is to be returned. @return an enumeration over the specified collection. @see EnumerationClass Collections, void fill(List, Object)
Replaces all of the elements of the specified list with the specified element.Class Collections, void reverse(List)This method runs in linear time. @param list the list to be filled with the specified element. @param
oobj The element with which to fill the specified list. @throws UnsupportedOperationException if the specified list'sor its list-iterator does not support the set operation.
Reverses the order of the elements in the specified list.Class Collections, void shuffle(List)This method runs in linear time. @param
llist the list whose elements are to be reversed. @throws UnsupportedOperationException if the specified list'sor its list-iterator does not support the setoperationmethod.
Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.Class Collections, void shuffle(List, Random)The hedge "approximately" is used in the foregoing description because default source of randomenss is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits then the algorithm would choose permutations with perfect uniformity.
This implementation traverses the list backwards from the last element up to the second repeatedly swapping a randomly selected element into the "current position". Elements are randomly selected from the portion of the list that runs from the first element to the current position inclusive.
This method runs in linear time.
for aIf the"randomspecifiedaccess"list does not implement the RandomAccess interface and is large this implementation dumps the specified list(whichintoprovidesannear-constant-timearraypositionalbeforeaccess)shuffling it and dumps the shuffled array back into the list.It may requireThis avoids the quadratictimebehavior that would resultforfrom shuffling a "sequential access" list in place. @param list the list to be shuffled. @throws UnsupportedOperationException if the specified list'sor its list-iterator does not support the setoperationmethod.
Randomly permute the specified list using the specified source of randomness. All permutations occur with equal likelihood assuming that the source of randomness is fair.Class Collections, List unmodifiableList(List)This implementation traverses the list backwards from the last element up to the second repeatedly swapping a randomly selected element into the "current position". Elements are randomly selected from the portion of the list that runs from the first element to the current position inclusive.
This method runs in linear time.
for aIf the"randomspecifiedaccess"list does not implement the RandomAccess interface and is large this implementation dumps the specified list(whichintoprovidesannear-constant-timearraypositionalbeforeaccess)shuffling it and dumps the shuffled array back into the list.It may requireThis avoids the quadratictimebehavior that would resultforfrom shuffling a "sequential access" list in place. @param list the list to be shuffled. @param rnd the source of randomness to use to shuffle the list. @throws UnsupportedOperationException if the specified list'sor its list-iterator does not support the set operation.
Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list and attempts to modify the returned list whether direct or via its iterator result in an UnsupportedOperationException.The returned list will be serializable if the specified list is serializable. Similarly the returned list will implement RandomAccess if the specified list does. the @param list the list for which an unmodifiable view is to be returned. @return an unmodifiable view of the specified list.
A comparison function which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as TreeSet or TreeMap).The ordering imposed by a Comparator c on a set of elements S is said to be consistent with equals if and only if (compare((Object)e1 (Object)e2)==0) has the same boolean value as e1.equals((Object)e2) for every e1 and e2 in S.
Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit Comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map) which is defined in terms of equals.
For example if one adds two keys a and b such that (a.equals((Object)b) && c.compare((Object)a (Object)b) = 0) to a sorted set with comparator c the second add operation will return false (and the size of the sorted set will not increase) because a and b are equivalent from the sorted set's perspective.
Note: It is generally a good idea for comparators to implement java.io.Serializable as they may be used as ordering methods in serializable data structures (like TreeSet TreeMap). In order for the data structure to serialize successfully the comparator (if provided) must implement Serializable.
For the mathematically inclined the relation that defines the total order that a given comparator c imposes on a given set of objects S is:
{(x y) such that c.compare((Object)x (Object)y) <= 0}.The quotient for this total order is:{(x y) such thatIt 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):xc.compareTocompare((Object)x (Object)y) == 0}.{(x y) such that x.equals((Object)y)}.@author Josh Bloch @version 1.15 0217 12/0203/0001 @see Comparable @see Arrays#sort(Object[] Comparator) @see TreeMap @see TreeSet @see SortedMap @see SortedSet @see java.io.Serializable @since 1.2
This exception may be thrown by methods that have detected concurrent modification ofa backingan object when such modification is not permissible.For example it is not generally permssible for one thread to modify a Collection while another thread is iterating over it. In general the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the collection implementations provided by the
SDKJRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators as they fail quickly and cleanly rather that risking arbitrary non-deterministic behavior at an undetermined time in the future.Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object the object may throw this exception. For example if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator the iterator will thow this exception.
Note that fail-fast behavior cannot be guaranteed as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast operations throw ConcurrentModificationException on a best-effort basis. Therefore it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs.
@author Josh Bloch @version 1.11 0214 12/0203/0001 @see Collection @see Iterator @see ListIterator @see Vector @see LinkedList @see HashSet @see Hashtable @see TreeMap @see AbstractList @since 1.2
The classClass Date, long UTC(int, int, int, int, int, int)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.
69 0271 12/0903/01 @see java.text.DateFormat @see java.util.Calendar @see java.util.TimeZone @since JDK1.0
Determines the date and time based on the arguments. The arguments are interpreted as a year month day of the month hour of the day minute within the hour and second within the minute exactly as for the Date constructor with six arguments except that the arguments are interpreted relative to UTC rather than to the local time zone. The timeClass Date, int getTimezoneOffset()indecatedindicated is returned represented as the distance measured in milliseconds of that time from the epoch (00:00:00 GMT on January 1 1970). @param year the year minus 1900. @param month the month between 0-11. @param date the day of the month between 1-31. @param hrs the hours between 0-23. @param min the minutes between 0-59. @param sec the seconds between 0-59. @return the number of milliseconds since January 1 1970 00:00:00 GMT for the date and time specified by the arguments. @see java.util.Calendar @deprecated As of JDK version 1.1 replaced byCalendar.set(year + 1900 month date hrs min sec)
orGregorianCalendar(year + 1900 month date hrs min sec)
using a UTCTimeZone
followed byCalendar.getTime().getTime()
.
Returns the offset measured in minutes for the local time zone relative to UTC that is appropriate for the time represented by this Date object.Class Date, String toGMTString()For example in Massachusetts five time zones west of Greenwich:
because on February 14 1996 standard time (Eastern Standard Time) is in use which is offset five hours from UTC; but:new Date(96 1 14).getTimezoneOffset() returns 300because on May 1 1996 daylight savings time (Eastern Daylight Time) is in use which is offset only four hours from UTC.new Date(96 5 1).getTimezoneOffset() returns 240This method produces
tehthe same result as if it computed:@return the time-zone offset in minutes for the current locale. @see java.util.Calendar @see java.util.TimeZone @deprecated As of JDK version 1.1 replaced by(this.getTime() - UTC(this.getYear() this.getMonth() this.getDate() this.getHours() this.getMinutes() this.getSeconds())) / (60 * 1000)Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)
.
Creates a string representation of this Date object of the form:Class Date, String toString()d mon yyyy hh:mm:ss GMTwhere:
- d is the day of the month (1 through 31) as one or two decimal digits.
- mon is the month (Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec).
- yyyy
i stheis the year as four decimal digits.- hh is the hour of the day (00 through 23) as two decimal digits.
- mm is the minute within the hour (00 through 59) as two decimal digits.
- ss is the second within the minute (00 through 61) as two decimal digits.
- GMT is exactly the ASCII letters "GMT" to indicate Greenwich Mean Time.
The result does not depend on the local time zone. @return a string representation of this date using the Internet GMT conventions. @see java.text.DateFormat @see java.util.Date#toString() @see java.util.Date#toLocaleString() @deprecated As of JDK version 1.1 replaced by
DateFormat.format(Date date)
using a GMTTimeZone
.
Converts thisDate
object to aString
of the form:where:dow mon dd hh:mm:ss zzz yyyy@return a string representation of this date. @see java.util.Date#toLocaleString() @see java.util.Date#toGMTString()
- dow is the day of the week (Sun Mon Tue Wed Thu Fri Sat).
- mon is the month (Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec).
- dd is the day of the month (01 through 31) as two decimal digits.
- hh is the hour of the day (00 through 23) as two decimal digits.
- mm is the minute within the hour (00 through 59) as two decimal digits.
- ss is the second within the minute (00 through 61 as two decimal digits.
- zzz is the time zone (and may reflect daylight savings time). Standard time zone abbreviations include those recognized by the method parse. If time zone
informationiinformation is not available then zzz is empty - that is it consists of no characters at all.- yyyy is the year as four decimal digits.
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.
15 0216 12/0203/0001 @see java.util.Map @see java.lang.Object#equals(java.lang.Object) @see java.lang.Object#hashCode() @see java.util.Hashtable @since JDK1.0
Thrown by methods in theStack
class to indicate that the stack is empty. @author Jonathan Payne @version 1.17 0218 12/0203/0001 @see java.util.Stack @since JDK1.0
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.
18 0219 12/0203/0001 @since JDK1.0
Class GregorianCalendar, void add(int, 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 the earliest seven 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 0or 1to4 or 56. 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
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.Example:
@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 hours5366 @author David Goldsmith Mark Davis Chen-Lieh Huang Alan Liu @since JDK1.1
Class GregorianCalendar, void roll(int, boolean)Overrides Calendar Date Arithmetic function.Adds the specified (signed) amount of time to the given time field based on the calendar's rules.Add rule 1. The value of
field
after the call minus the value offield
before the call isamount
modulo any overflow that has occurred infield
. 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
@param field the time field. @param amount the amount of date or time to be added to the field. @exception IllegalArgumentException if an unknown field is given.field
is changed then its value is adjusted to be as close as possible to its expected value. A smaller field represents a smaller unit of time.HOUR
is a smaller field 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.
Class GregorianCalendar, void roll(int, int)OverridesAddsCalendar Time Field Rolling function.orRollssubtracts (up/down) a single unit of time on the given time field without changing larger fields.@param@param up
fieldExample: Consider aGregorianCalendar
originally set to December 31 1999. Callingroll(Calendar.MONTH true)
sets thetimecalendar to January 31 1999. TheYear
field is unchanged because it is a larger field thanMONTH
.Indicatesindicates ifrollingthe value of the specified time field is to be rolled up orrollingrolled down.the fieldUse truevalueif rolling up false otherwise. @exception IllegalArgumentException if an unknown field value is given. @see GregorianCalendar#add @see GregorianCalendar#set
RollAdd to field a signed amount without changing larger fields. A negative roll amount means to subtract from field without changing larger fields.Example: Consider a
a larger fieldGregorianCalendar
originally set to August 31 1999. Callingroll(Calendar.MONTH 8)
sets the calendar to April 30 1999. Using aGregorianCalendar
theDAY_OF_MONTH
field cannot be 31 in the month April.DAY_OF_MONTH
is set to the closest possible value 30. TheYEAR
field maintains the value of 1999 because it isbythanMONTH
.Example:
Consider aGregorianCalendar
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). @param field the time field. @param amount the signed amount to add tofield
. @since 1.2 @see GregorianCalendar#add @see GregorianCalendar#set
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()This implementation provides constant-time performance for the basic operations (get and put) assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus it's very important not to set the
intialinitial capacity too high (or the load factor too low) if iteration performance is important.An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity the capacity is roughly doubled by calling the rehash method.
As a general rule the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor no rehash operations will ever occur.
If many mappings are to be stored in a HashMap instance creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table.
Note that this implementation is not synchronized. If multiple threads access this map concurrently and at least one of the threads modifies the map structurally it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time to prevent accidental unsynchronized access to the map:
Map m = Collections.synchronizedMap(new HashMap(...));The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created in any way except through the iterator's own remove or add methods the iterator will throw a ConcurrentModificationException. Thus in the face of concurrent modification the iterator fails quickly and cleanly rather than risking arbitrary non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. @author Doug Lea @author Josh Bloch @author Arthur van Hoff @version 1.
38 0250 12/0203/0001 @see Object#hashCode() @see Collection @see Map @see TreeMap @see Hashtable @since 1.2
ConstructsClass HashMap, constructor HashMap(Map)aannewemptymapHashMap withathe default initial capacity (16) andload factor which isthe default load factor (0.75).
Constructs a newClass HashMap, constructor HashMap(int)mapHashMap with the same mappings as thegivenspecifiedmapMap. ThemapHashMap is created witha capacity of twice the number of mappings indefaultthe givenload factormap(0.75)or 11and an(whicheverinitialiscapacitygreater)sufficientand a default load factor which isto hold the mappings in the specified0.75Map. @paramtm the map whose mappings are to be placed in this map. @throws NullPointerException if the specified map is null.
ConstructsClass HashMap, constructor HashMap(int, float)aannewemptymapHashMap with the specified initial capacity and the default load factorwhich is(0.75). @param initialCapacity the initial capacityof the HashMap. @throws IllegalArgumentException if the initial capacity isless than zeronegative.
ConstructsClass HashMap, boolean containsKey(Object)aannewemptymapHashMap with the specified initial capacity andthe specifiedload factor. @param initialCapacitytheThe initial capacityof the HashMap. @param loadFactortheThe load factorof the HashMap. @throws IllegalArgumentException if the initial capacity isless than zeronegative orifthe load factor is nonpositive.
Returns true if this map contains a mapping for the specified key. @param key The key whose presence in this map is to be tested @return true if this map contains a mapping for the specified key.Class HashMap, Object get(Object)@param key key whose presence in this Map is to be tested.
Returns the value to whichClass HashMap, void putAll(Map)this map mapsthe specified key.Returnsis mapped in this identity hash map or null if the map contains no mapping for this key. A return value of null does not necessarily indicate that the map contains no mapping for the key; it'sis also possible that the map explicitly maps the key to null. The containsKeyoperationmethod may be used to distinguish these two cases. @param key the key whose associated value is to be returned. @return the value to which this map maps the specified key.@paramorkeynullkey whose associated value is to beif the map contains no mapping forreturnedthis key. @see #put(Object Object)
Copies all of the mappings from the specified map to thisone.map These mappings will replace any mappings that this map had for any of the keys currently in the specifiedMapmap. @param tMappingsmappings to be stored in this map. @throws NullPointerException if the specified map is null.
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()This class offers constant time performance for the basic operations (add remove contains and size) assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus it's very important not to set the
intialinitial capacity too high (or the load factor too low) if iteration performance is important.Note that this implementation is not synchronized. If multiple threads access a set concurrently and at least one of the threads modifies the set it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time to prevent accidental unsynchronized access to the HashSet instance:
Set s = Collections.synchronizedSet(new HashSet(...));The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created in any way except through the iterator's own remove method the Iterator throws a ConcurrentModificationException. Thus in the face of concurrent modification the iterator fails quickly and cleanly rather than risking arbitrary non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. @author Josh Bloch @version 1.
19 0225 12/0203/0001 @see Collection @see Set @see TreeSet @see Collections#synchronizedSet(Set) @see HashMap @since 1.2
Constructs a new empty set; the backing HashMap instance has default initial capacity (16) and load factorClass HashSet, constructor HashSet(Collection)which is(0.75).
Constructs a new set containing the elements in the specified collection. TheClass HashSet, boolean remove(Object)capacity of the backingHashMapinstanceistwice the size of thecreated with default load factorspecified(0.75)collection or elevenand an initial(whichevercapacityissufficientgreater)toandcontain thedefault load factor (whichelementsisin0.75)theis usedspecified collection. @param c the collection whose elements are to be placed into this set. @throws NullPointerException if the specified collection is null.
Removes thegivenspecified element from this set if it is present. @param o object to be removed from this set if present. @return true if the set contained the specified element.
This class implements a hashtable which maps keys to values. Any non-Class Hashtable, constructor Hashtable()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 the Java 2 platform v1.2 this class has been retrofitted to implement Map so that it becomes a part of Java's collection framework. Unlike the new collection implementations Hashtable is synchronized.
The Iterators returned by the iterator and listIterator methods of the Collections returned by all of Hashtable's "collection view methods" are fail-fast: if the Hashtable is structurally modified at any time after the Iterator is created in any way except through the Iterator's own remove or add methods the Iterator will throw a ConcurrentModificationException. Thus in the face of concurrent modification the Iterator fails quickly and cleanly rather than risking arbitrary non-deterministic behavior at an undetermined time in the future. The Enumerations returned by Hashtable's keys and values methods are not fail-fast.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. @author Arthur van Hoff @author Josh Bloch @version 1.
84 0990 12/2413/01 @see Object#equals(java.lang.Object) @see Object#hashCode() @see Hashtable#rehash() @see Collection @see Map @see HashMap @see TreeMap @since JDK1.0
Constructs a new empty hashtable with a default initial capacity (11) and load factor which is 0.75.Class Hashtable, constructor Hashtable(Map)
Constructs a new hashtable with the same mappings as the given Map. The hashtable is created withClass Hashtable, boolean equals(Object)a capacity of twice the number of entriesan initial capacity sufficient to hold the mappings in the given Mapor 11 (whichever is greater)and a default load factor which is 0.75. @param t the map whose mappings are to be placed in this map. @throws NullPointerException if the specified map is null. @since 1.2
Compares the specified Object with this Map for equality as per the definition in the Map interface. @param o object to be compared for equality with this Hashtable @return true if the specified Object is equal to this Map. @see Map#equals(Object) @since 1.2Class Hashtable, void putAll(Map)
Copies all of the mappings from the specified Map to this Hashtable These mappings will replace any mappings that this Hashtable had for any of the keys currently in the specified Map. @param t Mappings to be stored in this map. @throws NullPointerException if the specified map is null. @since 1.2
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.
14 0216 12/0203/0001 @see Collection @see ListIterator @see Enumeration @since 1.2
Returns the next element in theinterationiteration. @return the next element in the iteration. @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.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. @author Josh Bloch @version 1.
32 0243 12/0203/0001 @see List @see ArrayList @see Vector @see Collections#synchronizedList(List) @since 1.2
Constructs a list containing the elements of the specified collection in the order they are returned by the collection's iterator. @param c the collection whose elements are to be placed into this list. @throws NullPointerException if the specified collection is null.Class LinkedList, boolean addAll(Collection)
Appends all of the elements in the specified collection to the end of this list in the order that they are returned by the specified collection's iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified Collection is this list and this list is nonempty.) @param c the elements to be inserted into this list. @Class LinkedList, boolean addAll(int, Collection)throwsreturnIndexOutOfBoundsExceptiontrue ifthe specified indexthis list changedisas aoutresult ofrangethe(indexcall.<@throws0NullPointerException||ifindexthe>specifiedsize())collection is null.
Inserts all of the elements in the specified collection into this list starting at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection's iterator. @param index index at which to insert first element from the specified collection. @param c elements to be inserted into this list. @return true if this list changed as a result of the call. @throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()). @throws NullPointerException if the specified collection is null.Class LinkedList, Object getFirst()
Returns the first element in this list. @return the first element in this list. @throws NoSuchElementException if this list is empty.Class LinkedList, Object[] toArray(Object[])
Returns an array containing all of the elements in this list in the correct order. The; the runtime type of the returned array is that of the specified array. If the list fits in the specified array it is returned therein. Otherwise a new array is allocated with the runtime type of the specified array and the size of this list.If the list fits in the specified array with room to spare (i.e. the array has more elements than the list) the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements. @param a the array into which the elements of the list are to be stored if it is big enough; otherwise a new array of the same runtime type is allocated for this purpose. @return an array containing the elements of the list. @throws ArrayStoreException if the runtime type of a is not a supertype of the runtime type of every element in this list. @throws NullPointerException if the specified array is null.
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 add(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.
Some list implementations have restrictions on the elements that they may contain. For example some implementations prohibit null elements and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface. @author Josh Bloch @version 1.
32 0236 12/0203/0001 @see Collection @see Set @see ArrayList @see LinkedList @see Vector @see Arrays#asList(Object[]) @see Collections#nCopies(int Object) @see Collections#EMPTY_LIST @see AbstractList @see AbstractSequentialList @since 1.2
Appends the specified element to the end of this list (optional operation).Class List, void add(int, Object)Lists that support this operation may place limitations on what elements may be added to this list. In particular some lists will refuse to add null elements and others will impose restrictions on the type of elements that may be added. List classes should clearly specify in their documentation any restrictions on what elements may be added. @param o element to be appended to this list. @return true (as per the general contract of the Collection.add method). @throws UnsupportedOperationException if the add method is not supported by this list. @throws ClassCastException if the class of the specified element prevents it from being added to this list. @throws NullPointerException if the specified element is null and this list does not support null elements. @throws IllegalArgumentException if some aspect of this element prevents it from being added to this
collectionlist.
Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). @param index index at which the specified element is to be inserted. @param element element to be inserted. @throws UnsupportedOperationException if the add method is not supported by this list. @throws ClassCastException if the class of the specified element prevents it from being added to this list. @throws NullPointerException if the specified element is null and this list does not support null elements. @throws IllegalArgumentException if some aspect of the specified element prevents it from being added to this list. @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > size()).Class List, boolean addAll(Collection)
Appends all of the elements in the specified collection to the end of this list in the order that they are returned by the specified collection's iterator (optional operation). The behavior of this operation is unspecified if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list and it's nonempty.) @param c collection whose elements are to be added to this list. @return true if this list changed as a result of the call. @throws UnsupportedOperationException if the addAll method is not supported by this list. @throws ClassCastException if the class of an element in the specified collection prevents it from being added to this list. @throws NullPointerException if the specified collection contains one or more null elements and this list does not support null elements or if the specified collection is null. @throws IllegalArgumentException if some aspect of an element in the specified collection prevents it from being added to this list. @see #add(Object)Class List, boolean addAll(int, Collection)
Inserts all of the elements in the specified collection into this list at the specified position (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in this list in the order that they are returned by the specified collection's iterator. The behavior of this operation is unspecified if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list and it's nonempty.) @param index index at which to insert first element from the specified collection. @param c elements to be inserted into this list. @return true if this list changed as a result of the call. @throws UnsupportedOperationException if the addAll method is not supported by this list. @throws ClassCastException if the class of one of elements of the specified collection prevents it from being added to this list. @throws NullPointerException if the specified collection contains one or more null elements and this list does not support null elements or if the specified collection is null. @throws IllegalArgumentException if some aspect of one of elements of the specified collection prevents it from being added to this list. @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > size()).Class List, boolean contains(Object)
Returns true if this list contains the specified element. More formally returns true if and only if this list contains at least one element e such that (o==null e==null : o.equals(e)). @param o element whose presence in this list is to be tested. @return true if this list contains the specified element. @throws ClassCastException if the type of the specified element is incompatible with this list (optional). @throws NullPointerException if the specified element is null and this list does not support null elements (optional).Class List, boolean containsAll(Collection)
Returns true if this list contains all of the elements of the specified collection. @param c collection to be checked for containment in this list. @return true if this list contains all of the elements of the specified collection. @throws ClassCastException if the types of one or more elements in the specified collection are incompatible with this list (optional). @throws NullPointerException if the specified collection contains one or more null elements and this list does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see # contains(Object)Class List, int indexOf(Object)
Returns the index in this list of the first occurrence of the specified element or -1 if this list does not contain this element. More formally returns the lowest index i such that (o==null get(i)==null : o.equals(get(i))) or -1 if there is no such index. @param o element to search for. @return the index in this list of the first occurrence of the specified element or -1 if this list does not contain this element. @throws ClassCastException if the type of the specified element is incompatible with this list (optional). @throws NullPointerException if the specified element is null and this list does not support null elements (optional).Class List, int lastIndexOf(Object)
Returns the index in this list of the last occurrence of the specified element or -1 if this list does not contain this element. More formally returns the highest index i such that (o==null get(i)==null : o.equals(get(i))) or -1 if there is no such index. @param o element to search for. @return the index in this list of the last occurrence of the specified element or -1 if this list does not contain this element. @throws ClassCastException if the type of the specified element is incompatible with this list (optional). @throws NullPointerException if the specified element is null and this list does not support null elements (optional).Class List, boolean remove(Object)
Removes the first occurrence in this list of the specified element (optional operation). If this list does not contain the element it is unchanged. More formally removes the element with the lowest index i such that (o==null get(i)==null : o.equals(get(i))) (if such an element exists). @param o element to be removed from this list if present. @return true if this list contained the specified element. @throws ClassCastException if the type of the specified element is incompatible with this list (optional). @throws NullPointerException if the specified element is null and this list does not support null elements (optional). @throws UnsupportedOperationException if the remove method is not supported by this list.Class List, boolean removeAll(Collection)
Removes from this list all the elements that are contained in the specified collection (optional operation). @param c collection that defines which elements will be removed from this list. @return true if this list changed as a result of the call. @throws UnsupportedOperationException if the removeAll method is not supported by this list. @throws ClassCastException if the types of one or more elements in this list are incompatible with the specified collection (optional). @throws NullPointerException if this list contains one or more null elements and the specified collection does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #remove(Object) @see #contains(Object)Class List, boolean retainAll(Collection)
Retains only the elements in this list that are contained in the specified collection (optional operation). In other words removes from this list all the elements that are not contained in the specified collection. @param c collection that defines which elements this set will retain. @return true if this list changed as a result of the call. @throws UnsupportedOperationException if the retainAll method is not supported by this list. @throws ClassCastException if the types of one or more elements in this list are incompatible with the specified collection (optional). @throws NullPointerException if this list contains one or more null elements and the specified collection does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #remove(Object) @see #contains(Object)Class List, Object set(int, Object)
Replaces the element at the specified position in this list with the specified element (optional operation). @param index index of element to replace. @param element element to be stored at the specified position. @return the element previously at the specified position. @throws UnsupportedOperationException if the set method is not supported by this list. @throws ClassCastException if the class of the specified element prevents it from being added to this list. @throws NullPointerException if the specified element is null and this list does not support null elements. @throws IllegalArgumentException if some aspect of the specified element prevents it from being added to this list. @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index >= size()).Class List, List subList(int, int)
Returns a view of the portion of this list between the specified fromIndex inclusive and toIndex exclusive. (If fromIndex and toIndex are equal the returned list is empty.) The returned list is backed by this list so non-structural changes in the returned list are reflected in this list and vice-versa. The returned list supports all of the optional list operations supported by this list.Class List, Object[] toArray(Object[])This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example the following idiom removes a range of elements from a list:
list.subList(from to).clear();Similar idioms may be constructed for indexOf and lastIndexOf and all of the algorithms in the Collections class can be applied to a subList.The semantics of
thisthe list returned by this method become undefined if the backing list (i.e. this list) is structurally modified in any way other than via the returned list. (Structural modifications are those that change the size of this list or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.) @param fromIndex low endpoint (inclusive) of the subList. @param toIndex high endpoint (exclusive) of the subList. @return a view of the specified range within this list. @throws IndexOutOfBoundsException for an illegal endpoint index value (fromIndex < 0 || toIndex > size || fromIndex > toIndex).
Returns an array containing all of the elements in this list in proper sequence; the runtime type of the returned array is that of the specified array. Obeys the general contract of the Collection.toArray(Object[]) method. @param a the array into which the elements of this list are to be stored if it is big enough; otherwise a new array of the same runtime type is allocated for this purpose. @return an array containing the elements of this list. @throws ArrayStoreException if the runtime type of the specified array is not a supertype of the runtime type of every element in this list. @throws NullPointerException if the specified array is null.
An iterator for lists that allows the programmer to traverse the list in either directionClass ListIterator, void add(Object)andmodify the list during iteration and obtain the iterator's current position in the list. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). In a list of length n there are n+1 valid index values from 0 to n inclusive.Element(0) Element(1) Element(2) ... Element(n) ^ ^ ^ ^ ^ Index: 0 1 2 3 n+1Note that the #remove and #set(Object) methods are not defined in terms of the cursor position; they are defined to operate on the last element returned by a call to #next or #previous()
@author Josh Bloch @version 1.16 0219 12/0203/0001 @see Collection @see List @see Iterator @see Enumeration @since 1.2
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 thisSetlist. @exception IllegalArgumentException if some aspect of this element prevents it from being added to thisCollectionlist.
ListResourceBundle
isaan 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 the key which must be aString
keyand the second element is the value associated with that key.[Right
nowThethere'sfollowingnoexampleerror-checkingshowscode to enforce this so you could specifytwo members of a resource bundle family withkey-valuethepairsbasethatname "MyResources".have"MyResources"something other than a String as ais the default member of the bundlekey.familyButandsince"MyResources_fr" is theinterfacesFrench member. These members aredefinedbasedinonListResourceBundle
terms(aofrelatedStringexampleany valueshows howwithyou can add akey thatbundle toisnthis family that't a String will bes based on a propertiesinaccessiblefile).]In the followingThe keys in this examplethe keysare of the form "s1"..etc. The actual keys are entirely up to your choice so long as they are the same as the keys you use in your program to retrieve the objects from the bundle. Keys are case-sensitive.MyResource is the default version of the bundle family and MyResource_fr is the french version:@see ResourceBundle @see PropertyResourceBundle @since JDK1.1//====================public classMyResourceMyResources extends ListResourceBundle { public Object[][] getContents() { return contents; } static final Object[][] contents = { // LOCALIZE THIS {"s1" "3"} // starting value in choiceThefield {disk \"s2{1}\""MyDiskcontains {0}."} //starting value in stringMessageFormatfieldpattern {"s3s2" "3 Mar 961"} //starting value in date field {"s4" "The disk '{1}'locationcontainedof {0}on {2}."} // initialin pattern {"s5s3" "0My Disk"} //first choice numbersample disk name {"s6s4" "no files"} // firstchoice value {"s7" "1"} // secondChoiceFormat choicenumber{"s8s5" "one file"} // secondchoice value {"s9" "2"} // thirdChoiceFormat choicenumber{"s10s6" "{0 number}|3files"} // thirdchoice value {"s11" "format threw an exception: {0}"} // generic exception message {"s12" "ERROR"} // what to show in field in case of error {"s14"ChoiceFormat"Result"} // label for formatted stuffchoice {"s13s7" "Dialog"} // standard font3{"s15"Mar"Pattern96"} //label for standardsamplepatterndate {"s16s8" new Dimension(1 5)} // real object not just string // END OF MATERIAL TO LOCALIZE }; }//====================public classMyResourceMyResources_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" "Lediskdisque'\"{1}' a\" {0}a {2}."} //initialMessageFormat pattern {"s5s2" "01"} //first choicelocationnumberof {"s6" "pas de files"0}// first choiceinvaluepattern {"s7s3" "1Mon disque"} //second choice numbersample disk name {"s8"s4"unefile"} // secondnechoice valuecontient pas{"s9"de"2fichiers"} //third choice numberfirst ChoiceFormat choice {"s10s5" "{0}|3contientfilesun fichier"} //third choice valuesecond ChoiceFormat choice {"s11s6" "Le format acontientjete une exception:{0}"} // generic exception message {"s12""ERROR"number}// what to show in field in case of error {"s14"fichiers"Resulte"} //label forthirdformatted stuffChoiceFormat choice {"s13s7" "Dialogue"} // standard font3{"s15"mars"Pattern1996"} //label for standardsamplepatterndate {"s16s8" 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 createCreate aLocale
object usingone ofthetwoconstructors in this class:TheLocale(String language) Locale(String language String country) Locale(String language String country String variant)
firstlanguage argumentto both constructorsis a valid ISO Language Code. These codes are the lower-case two-letter codes as defined by ISO-639. You can find a full list of these codes at a number of sites such as:
http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt
The
secondcountry argumentto both constructorsis a valid ISO Country Code. These codes are the upper-case two-letter codes as defined by ISO-3166. You can find a full list of these codes at a number of sites such as:
http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html
The
second constructor requires a thirdvariant argument--the Variant. The Variantcodes areis a vendorandor browser-specific code. For example use WIN for Windows MAC for Macintosh and POSIX for POSIX. Where there are two variants separate them with an underscore and put the most important one first. For example a Traditional Spanish collation might construct a locale with parameters for language country and variant as: "es" "ES" "Traditional_WIN".Because a
Locale
object is just an identifier for a region no validity check is performed when you construct 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 Java 2 platform provides a number of classes that perform locale-sensitive operations. For example the
NumberFormat
class formats numbers currency or percentages in a locale-sensitive manner. Classes such 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.55 0168 12/1903/0001 @author Mark Davis @sinceJDK11.1
Construct a locale from language country.Class Locale, constructor Locale(String, String, String)To create a locale that only identifies a language use "" for the country.NOTE: ISO 639 is not a stable standard; some of the language codes it defines (specifically iw ji and in) have changed. This constructor accepts both the old codes (iw ji and in) and the new codes (he yi and id) but all other API on Locale will return only the OLD codes. @param language lowercase two-letter ISO-639 code. @param country uppercase two-letter ISO-3166 code. @exception NullPointerException thrown if either argument is null.
Construct a locale from language country variant. NOTE: ISO 639 is not a stable standard; some of the language codes it defines (specifically iw ji and in) have changed. This constructor accepts both the old codes (iw ji and in) and the new codes (he yi and id) but all other API on Locale will return only the OLD codes. @param language lowercase two-letter ISO-639 code. @param country uppercase two-letter ISO-3166 code. @param variant vendor and browser specific code. See class description. @exception NullPointerException thrown if any argument is null.Class Locale, String getISO3Language()
Returns a three-letter abbreviation for this locale's language. If the locale doesn't specify a language this will be the empty string. Otherwise this will be a lowercase ISO 639-2/T language code. The ISO 639-2 language codes can be found on-line atClass Locale, String toString()http://www.triacom.com/archive/iso639-2.en.html andftp://dkuug.dk/i18n/iso-639-2.txt
@exception MissingResourceException Throws MissingResourceException if the three-letter language abbreviation is not available for this locale.
Getter for the programmatic name of the entire locale with the language country and variant separated by underbars. Language is always lower case and country is always upper case. If the language is missing the string will begin with an underbar. If both the language and country fields are missing this function will return the empty string even if the variant field is filled in (you can't have a locale with just a variant-- the variant must accompany a valid language or country code). Examples: "en" "de_DE" "_GB" "en_US_WIN" "de__POSIX" "fr__MAC" @see #getDisplayName
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.Class Map, boolean containsKey(Object)This interface takes the place of the Dictionary class which was a totally abstract class rather than an interface.
The Map interface provides three collection views which allow a map's contents to be viewed as a set of keys collection of values or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations like the TreeMap class make specific guarantees as to their order; others like the HashMap class do not.
Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value extreme caution is advised: the equals and hashCode methods are no longer well defined on a such a map.
All general-purpose map implementation classes should provide two "standard" constructors: a void (no arguments) constructor which creates an empty map and a constructor with a single argument of type Map which creates a new map with the same key-value mappings as its argument. In effect the latter constructor allows the user to copy any map producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the SDK comply.
The "destructive" methods contained in this interface that is the methods that modify the map on which they operate are specified to throw UnsupportedOperationException if this map does not support the operation. If this is the case these methods may but are not required to throw an UnsupportedOperationException if the invocation would have no effect on the map. For example invoking the #putAll(Map) method on an unmodifiable map may but is not required to throw the exception if the map whose mappings are to be "superimposed" is empty.
Some map implementations have restrictions on the keys and values they may contain. For example some implementations prohibit null keys and values and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible key or value may throw an exception or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.
@author Josh Bloch @version 1.32 0237 12/0203/0001 @see HashMap @see TreeMap @see Hashtable @see SortedMap @see Collection @see Set @since 1.2
Returns true if this map contains a mapping for the specified key. More formally returns true if and only if this map contains at a mapping for a key k such that (key==null k==null : key.equals(k)). (There can be at most one such mapping.) @param key key whose presence in this map is to be tested. @return true if this map contains a mapping for the specified key. @throws ClassCastException if the key is of an inappropriate type for this map (optional). @throws NullPointerException if the key is null and this map does not not permit null keys (optional).Class Map, boolean containsValue(Object)
Returns true if this map maps one or more keys to the specified value. More formally returns true if and only if this map contains at least one mapping to a value v such that (value==null v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations of the Map interface. @param value value whose presence in this map is to be tested. @return true if this map maps one or more keys to the specified value. @throws ClassCastException if the value is of an inappropriate type for this map (optional). @throws NullPointerException if the value is null and this map does not not permit null values (optional).Class Map, Set entrySet()
Returns a set view of the mappings contained in this map. Each element in the returned set is a Map.EntryClass Map, Object get(Object).The set is backed by the map so changes to the map are reflected in the set and vice-versa. If the map is modified while an iteration over the set is in progress the results of the iteration are undefined. The set supports element removal which removes the corresponding mapping from the map via the Iterator.remove Set.remove removeAll retainAll and clear operations. It does not support the add or addAll operations. @return a set view of the mappings contained in this map.
Returns the value to which this map maps the specified key. Returns null if the map contains no mapping for this key. A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.Class Map, Object put(Object, Object)More formally if this map contains a mapping from a key k to a value v such that (key==null k==null : key.equals(k)) then this method returns v; otherwise it returns null. (There can be at most one such mapping.) @param key key whose associated value is to be returned. @return the value to which this map maps the specified key or null if the map contains no mapping for this key. @throws ClassCastException if the key is of an inappropriate type for this map (optional). @throws NullPointerException key is null and this map does not not permit null keys (optional). @see #containsKey(Object)
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for this key the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)) @param key key with which the specified value is to be associated. @param value value to be associated with the specified key. @return previous value associated with specified key or null if there was no mapping for key. A null return can also indicate that the map previously associated null with the specified key if the implementation supports null values. @throws UnsupportedOperationException if the put operation is not supported by this map. @throws ClassCastException if the class of the specified key or value prevents it from being stored in this map. @throws IllegalArgumentException if some aspect of this key or value prevents it from being stored in this map. @throws NullPointerException this map does not permit null keys or values and the specified key or value is null.Class Map, void putAll(Map)
Copies all of the mappings from the specified map to this map (optional operation).Class Map, Object remove(Object)TheseThemappingseffect ofwill replace any mappingsthis call is equivalent to that of calling Object put(k v)} on this maphadonce foranyeachof themapping fromkeyskey k tocurrentlyvalue v in the specified map. The behavior of this operation is unspecified if the specified map is modified while the operation is in progress. @param t Mappings to be stored in this map. @throws UnsupportedOperationException if the putAll method is not supported by this map. @throws ClassCastException if the class of a key or value in the specified map prevents it from being stored in this map. @throws IllegalArgumentException some aspect of a key or value in the specified map prevents it from being stored in this map. @throws NullPointerException the specified map is null or if this map does not permit null keys or values and the specifiedkey or valuemapiscontains null keys or values.
Removes the mapping for this key from this map if it is present (optional operation).@paramMore formally if this map contains a mapping from key k to value v such that(
key==null k==null : key.equals(k))whosethat mapping istoremoved.be(Theremoved from themap can containmapat most one such mapping.)@returnReturns
previousthe valueassociatedtowithwhichspecifiedthe map previously associated the key or null iftherethewasmap contained no mapping for this key. (A null return can also indicate that the map previously associated null with the specified key if the implementation supports null values.) The map will not contain a mapping for the specified key once the call returns. @param key key whose mapping is to be removed from the map. @return previous value associated with specified key or null if there was no mapping for key. @throws ClassCastException if the key is of an inappropriate type for this map (optional). @throws NullPointerException if the key is null and this map does not not permit null keys (optional). @throws UnsupportedOperationException if the remove method is not supported by this map.
Signals that a resource is missing. @see java.lang.Exception @see ResourceBundle @version 1.Class MissingResourceException, constructor MissingResourceException(String, String, String)12 0114 12/1903/0001 @author Mark Davis @since JDK1.1
Constructs a MissingResourceException with the specified information. A detail message is a String that describes this particular exception. @param s the detail message @paramClass MissingResourceException, String getClassName()classnameclassName the name of the resource class @param key the key for the missing resource.
Gets parameter passed by constructor. @return the name of the resource classClass MissingResourceException, String getKey()
Gets parameter passed by constructor. @return the key for the missing resource
Thrown by thenextElement
method of anEnumeration
to indicate that there are no more elements in the enumeration. @author unascribed @version 1.18 0219 12/0203/0001 @see java.util.Enumeration @see java.util.Enumeration#nextElement() @since JDK1.0
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, void addObserver(Observer)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
threaadsthreads or may guarantee that their subclass follows this order as they choose.Note that this notification mechanism is has nothing to do with threads and is completely separate from the wait and notify mechanism of class Object.
When an observable object is newly created its set of observers is empty. Two observers are considered the same if and only if the equals method returns true for them. @author Chris Warth @version 1.
31340212/0203/0001 @see java.util.Observable#notifyObservers() @see java.util.Observable#notifyObservers(java.lang.Object) @see java.util.Observer @see java.util.Observer#update(java.util.Observable java.lang.Object) @since JDK1.0
Adds an observer to the set of observers for this object provided that it is not the same as some observer already in the set. The order in which notifications will be delivered to multiple observers is not specified. See the class comment. @param o an observer to be added. @throws NullPointerException if the parameter o is null.
A class can implement theObserver
interface when it wants to be informed of changes in observable objects. @author Chris Warth @version 1.16 0217 12/0203/0001 @see java.util.Observable @since JDK1.0
TheClass Properties, Enumeration propertyNames()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.
60 0264 06/0226/00 @since JDK1.0
Returns an enumeration of all the keys in this property list includingClass Properties, Object setProperty(String, String)thedistinct keys in the default property list if a key of the same name has not already been found from the main properties list. @return an enumeration of all the keys in this property list including the keys in the default property list. @see java.util.Enumeration @see java.util.Properties#defaults
Calls theClass Properties, void store(OutputStream, String)hashtableHashtable methodput
. Provided for parallelism with the getProperty method. Enforces use of strings for property keys and values. The value returned is the result of the Hashtable call toput
. @param key the key to be placed into this property list. @param value the value corresponding to key. @return the previous value of the specified key in this property list ornull
if it did not have one. @see #getProperty @since 1.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 than\u0020
and characters greater than\u007E
are written as\u
xxxx for the appropriate hexadecimal value xxxx. Leading space characters but not embedded or trailing space characters are written with a preceding\
. The key and value characters#
=
and:
are written with a preceding slash to ensure that they are properly loaded.After the entries have been written the output stream is flushed. The output stream remains open after this method returns. @param out an output stream. @param header a description of the property list. @exception IOException if writing this property list to the specified output stream throws an IOException. @exception ClassCastException if this
Properties
object contains any keys or values that are notStrings
. @exception NullPointerException ifout
is null. @since 1.2
This class is for property permissions.Class PropertyPermission, boolean implies(Permission)The name is the name of the property ("java.home" "os.name" etc). The naming convention follows the hierarchical property naming convention. Also an asterisk may appear at the end of the name following a "." or by itself to signify a wildcard match. For example: "java.*" or "*" is valid "*java" or "a*b" is not valid.
The actions to be granted are passed to the constructor in a string containing a list of zero or more comma-separated keywords. The possible keywords are "read" and "write". Their meaning is defined as follows:
- read
- read permission. Allows
System.getProperty
to be called.- write
- write permission. Allows
System.setProperty
to be called.The actions string is converted to lowercase before processing.
Care should be taken before granting code permission to access certain system properties. For example granting permission to access the "java.home" system property gives potentially malevolent code sensitive information about the system environment (the Java installation directory). Also granting permission to access the "user.name" and "user.home" system properties gives potentially malevolent code sensitive information about the user environment (the user's account name and home directory). @see java.security.BasicPermission @see java.security.Permission @see java.security.Permissions @see java.security.PermissionCollection @see java.lang.SecurityManager @version 1.
24 0027 01/0212/0203 @author Roland Schemers @since 1.2 @serial exclude
Checks if this PropertyPermission object "implies" the specified permission.More specifically this method returns true if:
@param p the permission to check against. @return true if the specified permission is implied by this object false if not.
- p is an instanceof PropertyPermission
- p's actions are a
propersubset of this object's actions and
- p's name is implied by this object's name. For example "java.*" implies "java.home".
Class PropertyResourceBundle, constructor PropertyResourceBundle(InputStream)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 in particular the information on character encodings.Unlike other types of resource bundle you don't subclass
PropertyResourceBundle
. Instead you supply properties files containing the resource data.ResourceBundle.getBundle
will automatically look for the appropriate properties file and create a()PropertyResourceBundle
that refers to it.The resource bundle name that youSeepassjava.util.Localtojava.lang.ClassLoader) ResourceBundle.getBundle()}is the file namefor a complete description of thepropertiessearchfile notand instantiationthestrategy.class name ofThe following
theexampleobject that isshows a memberreturned.ofFor example if you saya resource bundle family with theResourceBundle.getBundle(base name "MyResources".newTheLocale("fr"text"FR"));defines theresourcebundlelookup"MyResources_de"mechanism willthe Germansearchmember of theclassbundlepathfamily.for a fileThis member iscalledbased on
MyResources_fr_FR.propertiesPropertyResourceBundle.If a real class and aand the text therefore is the contentpropertiesof the filewith"MyResources_de.properties" (aparticular name both exist the classrelatedwins;examplethe properties file will only be used if there is no class with the desiredshows how you can add bundles to this family that are implemented as subclasses ofnameListResourceBundle
).In the followingThe keys in this examplethe keysare of the form "s1"..etc. The actual keys are entirely up to your choice so long as they are the same as the keys you use in your program to retrieve the objects from the bundle. Keys are case-sensitive.@see ResourceBundle @see ListResourceBundle @see Properties @since JDK1.1s1=3 s2=MeinDisk s3=3#Mar 96 s4MessageFormat pattern s1=DerDiediskPlatte'\"{1}'\"aenthält {0}.a#{2}.locations5=of {0}s6=keineinDatein s7pattern s2=1s8=ein#Dateisample disk names9s3=2Meine Platte # first ChoiceFormat choices10s4={0}|3keine DateienDatein#s11second ChoiceFormat choice s5=Dereine DateiFormat worf ein# third ChoiceFormatException:choice s6={0 number}s12=ERRORDateiens14=Resulte#s13=Dialoguesamples15=Patterndates16s7=13. März 1996
Creates a property resource bundle. @param stream property file to read from.
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, constructor Random()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.34 0236 12/0203/0001 @see java.lang.Math#random() @since JDK1.0
Creates a new random number generator. Its seed is initialized to a value based on the current time:Two Random objects created within the same millisecond will have the same sequence of random numbers. @see java.lang.System#currentTimeMillis()public Random() { this(System.currentTimeMillis()); }
Resource bundles contain locale-specific objects. When your program needs a locale-specific resource aClass ResourceBundle, ResourceBundle getBundle(String)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 classesResourcethat inherit frombundles belong toResourceBundle.familiesEach related subclass ofwhose members share aResourceBundlecommonhas the same base name plus anbase name but whose names also have additionalcomponentcomponents thatidentifies its localeidentify their locales. For examplesupposetheyour resource bundle is namedbase name of a familyMyResources.ofThe first class youresource bundles might beare"MyResources".likely to write is theThe family should have a default resource bundle which simply has the same name as its family-- "MyResources" - and will be used as the bundle of last resort if a specific locale is not supported.YouThe family canalsothen provide as manyrelatedlocale-specificclassesmembers asyou need:needed for exampleperhaps you would providea German one named "MyResources_de".Each
related subclass ofresource bundle inResourceBundlea family contains the same items but the items have been translated for the locale represented by thatResourceBundleresourcesubclassbundle. For example both "MyResources" and "MyResources_de" may have aString
that's used on a button for canceling operations. In "MyResources" theString
may contain "Cancel" and in "MyResources_de" it may contain "Abbrechen".If there are different resources for different countries you can make specializations: for example "MyResources_de_CH"
iscontains objects for the German language (de) in Switzerland (CH). If you want to only modify some of the resources in the specialization you can do so.When your program needs a locale-specific object it loads the
ResourceBundle
class using the java.util.Locale getBundle} method:ResourceBundle myResources = ResourceBundle.getBundle("MyResources" currentLocale);The first argument specifies the family name of the resource bundle that contains the object in question. The second argument indicates the desired locale. getBundle uses these two arguments to construct the name of the ResourceBundle subclass it should load as follows. The resource bundle lookup searches for classes with various suffixes on the basis of (1) the desired locale and (2) the current default locale as returned by Locale.getDefault() and (3) the root resource bundle (baseclass) in the following order from lower-level (more specific) to parent-level (less specific): baseclass + "_" + language1 + "_" + country1 + "_" + variant1 baseclass + "_" + language1 + "_" + country1 + "_" + variant1 + ".properties" baseclass + "_" + language1 + "_" + country1 baseclass + "_" + language1 + "_" + country1 + ".properties" baseclass + "_" + language1 baseclass + "_" + language1 + ".properties" baseclass + "_" + language2 + "_" + country2 + "_" + variant2 baseclass + "_" + language2 + "_" + country2 + "_" + variant2 + ".properties" baseclass + "_" + language2 + "_" + country2 baseclass + "_" + language2 + "_" + country2 + ".properties" baseclass + "_" + language2 baseclass + "_" + language2 + ".properties" baseclass baseclass + ".properties" For example if the current default locale is en_US the locale the caller is interested in is fr_CH and the resource bundle name is MyResources resource bundle lookup will search for the following classes in order: MyResources_fr_CH MyResources_fr MyResources_en_US MyResources_en MyResources The result of the lookup is a class but that class may be backed by a properties file on disk. That is if getBundle does not find a class of a given name it appends ".properties" to the class name and searches for a properties file of that name. If it finds such a file it creates a new PropertyResourceBundle object to hold it. Following on the previous example it will return classes and and files giving preference as follows: (class) MyResources_fr_CH (file) MyResources_fr_CH.properties (class) MyResources_fr (file) MyResources_fr.properties (class) MyResources_en_US (file) MyResources_en_US.properties (class) MyResources_en (file) MyResources_en.properties (class) MyResources (file) MyResources.properties If a lookup fails getBundle() throws a MissingResourceException. The baseclass must be fully qualified (for example myPackage.MyResources not just MyResources). It must also be accessable by your code; it cannot be a class that is private to the package where ResourceBundle.getBundle is called. Note: ResourceBundles are used internally in accessing NumberFormats Collations and so on. The lookup strategy is the same.Resource bundles contain key/value pairs. The keys uniquely identify a locale-specific object in the bundle. Here's an example of a
ListResourceBundle
that contains two key/value pairs:Keys are alwayspublic classMyResourceMyResources 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 are "OkKey" and "CancelKey". In the above example the values are alsoString
s--"OK" and "Cancel"--but they don't have to be. The values can be any type of object.You retrieve an object from resource bundle using the appropriate getter method. Because "OkKey" and "CancelKey" are both strings you would use
getString
to retrieve them: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(myResourceBundlemyResources.getString("OkKey")); button2 = new Button(myResourceBundlemyResources.getString("CancelKey"));MissingResourceException
.Besides
getString
;ResourceBundlesupports a numberalsoof other methodsprovides a method for gettingdifferent types of objectsstringsucharraysasgetStringArray
.If youas welldon'tashave ana genericobjectgetObject
that matches one of these methodsmethod for any other type ofyouobject.can useWhen usinggetObject
andyou'll have to cast the result to the appropriate type. For example:int[] myIntegers = (int[]) myResources.getObject("intList");
NOTE: You should always supply a baseclass with no suffixes. This will be the class of "last resort" if a locale is requested that does not exist. In fact you must provide all of the classes in any given inheritance chain that you provide a resource for. For example if you provide MyResources_fr_BE you must provide both MyResources and MyResources_fr or the resource bundle lookup won't work right.The Java 2 platform provides two subclasses 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 thatif the key is not found handleGetObject must return null. If the key is null a NullPointerException should be thrown. Notice also thatyou don't need to supply a value if a "parent-level"ResourceBundle
handles the same key with the same value (asin United Kingdomfor the okKey below).Also notice that because you specify an en_GB resource bundle you also have to provide a default en resource bundle even though it inherits all its data from the root resource bundle.Example:
You do not have to restrict yourself to using a single family of// default (English language United States)abstractpublic class MyResources extends ResourceBundle { public Object handleGetObject(String key) { if (key.equals("okKey")) return "Ok"; if (key.equals("cancelKey")) return "Cancel"; return null; } } // German language public class MyResources_de extends MyResources { public Object handleGetObject(String key) { // don't need okKey since parent level handles it. if (key.equals("cancelKey")) return "Abbrechen"; return null; } }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
Class ResourceBundle, ResourceBundle getBundle(String, Locale)GetGets a resource bundle using the specified base name the default locale and the caller's class loader. Calling this method is equivalent to callingexcept thatgetBundle(baseName Locale.getDefault() this.getClass().getClassLoader())
getClassLoader()
is run with theappropriatesecurity privileges ofResourceBundle
. See java.util.Local java.lang.ClassLoader) getBundle} for a complete descriptionsubclassof the search and instantiation strategy. @param baseNameseethe base name of the resource bundle a fully qualified classdescriptionname @exception java.lang.NullPointerException ifbaseName
isnull
@exception MissingResourceException if no resource bundle for the specified base name can be found @return a resource bundle for the given base name and the default locale
Class ResourceBundle, Enumeration getKeys()GetGets a resource bundle using the specified base name and locale and the caller's class loader. Calling this method is equivalent to callingexcept thatgetBundle(baseName locale this.getClass().getClassLoader())
getClassLoader()
is run with theappropriatesecurity privileges ofResourceBundle. See java.util.Local
subclassjava.lang.ClassLoader) getBundle} for a complete description of the search and instantiation strategy. @param baseNameseethe base name of the resource bundle a fully qualified classdescription.name @param localesee classthe localedescriptionfor which a resource bundle is desired @exception java.lang.NullPointerException ifbaseName
orlocale
isnull
@exception MissingResourceException if no resource bundle for the specified base name can be found @return a resource bundle for the given base name and locale
Class ResourceBundle, Locale getLocale()ReturnReturns an enumeration of the keys.NOTE: Subclasses must override.
Class ResourceBundle, Object getObject(String)ReturnReturns theLocalelocaleforof thisResourceBundleresource bundle.(Thisfunctionmethod can be used after a call to getBundle() to determine whether theResourceBundleresource bundle returned really corresponds to the requested locale or is a fallback.)@return the locale of this resource bundle
Class ResourceBundle, String getString(String)GetGets an object for the given key from this resource bundle or one of its parents. This method first tries to obtain the object from this resource bundle using handleGetObject If not successful and the parent resource bundle is not null it calls the parent'sgetObject
method. If still not successful it throws aResourceBundleMissingResourceException. @param keyseetheclasskeydescription.for the desired object @exception NullPointerException ifkey
isnull
.@exception MissingResourceException if no object for the given key can be found @return the object for the given key
Class ResourceBundle, String[] getStringArray(String)Get anGets aobjectstring for the given key fromathis resource bundleResourceBundleor one of its parents.ConvenienceCalling this method is equivalent tosavecallingcasting.@param key(String) getObject}(key)
seethe key forclassthedescription.desired string @exception NullPointerException ifkey
isnull
.@exception MissingResourceException if no object for the given key can be found @exception ClassCastException if the object found for the given key is not a string @return the string for the given key
Class ResourceBundle, Object handleGetObject(String)Get anGets aobjectstring array for the given key fromathis resource bundleResourceBundleor one of its parents.ConvenienceCalling this method is equivalent tosavecallingcasting.@param key(String[]) getObject}(key)
seethe key forclassthedescription.desired string array @exception NullPointerException ifkey
isnull
.@exception MissingResourceException if no object for the given key can be found @exception ClassCastException if the object found for the given key is not a string array @return the string array for the given key
Class ResourceBundle, void setParent(ResourceBundle)GetGets an object for the given key fromathis resourceResourceBundlebundle.NOTE:Returns null if this resource bundle does not contain an object forSubclassesthemust overridegiven key. @param keyseetheclasskeydescription.for the desired object @exception NullPointerException ifkey
isnull
.@return the object for the given key or null
Class ResourceBundle, ResourceBundle parentSetSets the parent bundle of this bundle. The parent bundle is searched by getObject when this bundle does not contain a particular resource. @param parent this bundle's parent bundle.
The parent bundle of this bundle. The parent bundle isconsultedsearched by getObject when this bundle does not contain a particular resource.
A collection that contains no duplicate elements. More formally sets contain no pair of elementsClass Set, boolean add(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.
Some set implementations have restrictions on the elements that they may contain. For example some implementations prohibit null elements and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the set may throw an exception or it may succeed at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface. @author Josh Bloch @version 1.
23 0227 12/0203/0001 @see Collection @see List @see SortedSet @see HashSet @see TreeSet @see AbstractSet @see Collections#singleton(java.lang.Object) @see Collections#EMPTY_SET @since 1.2
Adds the specified element to this set if it is not already present (optional operation). More formally adds the specified elementClass Set, boolean addAll(Collection)o
to this set if this set contains no elemente
such that(o==null e==null : o.equals(e))
. If this set already contains the specified element the call leaves this set unchanged and returns false. In combination with the restriction on constructors this ensures that sets never contain duplicate elements.The stipulation above does not imply that sets must accept all elements; sets may refuse to add any particular element including null and throwing an exception as described in the specification for Collection.add. Individual set implementations should clearly document any restrictions on the the elements that they may contain. @param o element to be added to this set. @return true if this set did not already contain the specified element. @throws UnsupportedOperationException if the add method is not supported by this set. @throws ClassCastException if the class of the specified element prevents it from being added to this set. @throws NullPointerException if the specified element is null and this set does not support null elements. @throws IllegalArgumentException if some aspect of
thisthe specified element prevents it from being added to this set.
Adds all of the elements in the specified collection to this set if they're not already present (optional operation). If the specified collection is also a set the addAll operation effectively modifies this set so that its value is the union of the two sets. The behavior of this operation is unspecified if the specified collection is modified while the operation is in progress. @param c collection whose elements are to be added to this set. @return true if this set changed as a result of the call. @throws UnsupportedOperationException if the addAll method is not supported by this set. @throws ClassCastException if the class of some element of the specified collection prevents it from being added to this set. @throws NullPointerException if the specified collection contains one or more null elements and this set does not support null elements or if the specified collection is null. @throws IllegalArgumentException if some aspect of some element of the specified collection prevents it from being added to this set. @see #add(Object)Class Set, boolean contains(Object)
Returns true if this set contains the specified element. More formally returns true if and only if this set contains an elementClass Set, boolean containsAll(Collection)e
such that(o==null e==null : o.equals(e))
. @param o element whose presence in this set is to be tested. @return true if this set contains the specified element. @throws ClassCastException if the type of the specified element is incompatible with this set (optional). @throws NullPointerException if the specified element is null and this set does not support null elements (optional).
Returns true if this set contains all of the elements of the specified collection. If the specified collection is also a set this method returns true if it is a subset of this set. @param c collection to be checked for containment in this set. @return true if this set contains all of the elements of the specified collection. @throws ClassCastException if the types of one or more elements in the specified collection are incompatible with this set (optional). @throws NullPointerException if the specified collection contains one or more null elements and this set does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #contains(Object)Class Set, boolean remove(Object)
Removes the specified element from this set if it is present (optional operation). More formally removes an elementClass Set, boolean removeAll(Collection)e
such that(o==null e==null : o.equals(e))
if the set contains such an element. Returns true if the set contained the specified element (or equivalently if the set changed as a result of the call). (The set will not contain the specified element once the call returns.) @param o object to be removed from this set if present. @return true if the set contained the specified element. @throws ClassCastException if the type of the specified element is incompatible with this set (optional). @throws NullPointerException if the specified element is null and this set does not support null elements (optional). @throws UnsupportedOperationException if the remove method is not supported by this set.
Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets. @param c collection that defines which elements will be removed from this set. @return true if this set changed as a result of the call. @throws UnsupportedOperationException if the removeAll method is not supported by this Collection. @throws ClassCastException if the types of one or more elements in this set are incompatible with the specified collection (optional). @throws NullPointerException if this set contains a null element and the specified collection does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #remove(Object)Class Set, boolean retainAll(Collection)
Retains only the elements in this set that are contained in the specified collection (optional operation). In other words removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set this operation effectively modifies this set so that its value is the intersection of the two sets. @param c collection that defines which elements this set will retain. @return true if this collection changed as a result of the call. @throws UnsupportedOperationException if the retainAll method is not supported by this Collection. @throws ClassCastException if the types of one or more elements in this set are incompatible with the specified collection (optional). @throws NullPointerException if this set contains a null element and the specified collection does not support null elements (optional). @throws NullPointerException if the specified collection is null. @see #remove(Object)Class Set, Object[] toArray(Object[])
Returns an array containing all of the elements in this set;whosethe runtime type of the returned array is that of the specified array. Obeys the general contract of the Collection.toArray(Object[]) method. @param a the array into which the elements of this set are to be stored if it is big enough; otherwise a new array of the same runtime type is allocated for this purpose. @return an array containing the elements of this set. @throws ArrayStoreException the runtime type of a is not a supertype of the runtime type of every element in this set. @throws NullPointerException if the specified array is null.
Class SimpleTimeZone, constructor SimpleTimeZone(int, String)SimpleTimeZone
is a concrete subclass ofTimeZone
that represents a time zone for use with a Gregorian calendar.ThisThe classdoesholdsnotan offset from GMT called raw offset and start and end rules for a daylight saving time schedule. Since it only holds single values for each it cannot handle historical changes.Use a negative value forin the offset from GMT anddayOfWeekInMonththetodaylight savingindicateschedule except that the setStartYear method can specify the year when the daylight saving time schedule starts in effect.To construct a
SimpleTimeZone
should count fromwith a daylight saving time schedule the schedule can be described with a set of rules start-rule and end-rule. A day when daylight saving time starts or ends is specified by a combination of month day-of-month and day-of-week values. The month value is represented by a Calendar MONTH field value such as Calendar#MARCH The day-of-week value is represented by a Calendar DAY_OF_WEEK value such as SUNDAY The meanings of value combinations are as follows.21st of March set month to MARCH day-of-month is -21 and day-of-week is -WEDNESDAY
- Exact day of month
To specify an exact day of month set the month and day-of-month to an exact value and day-of-week to zero. For example to specify March 1 set the month to MARCH day-of-month to 1 and day-of-week to 0.- Day of week on or after day of month
To specify a day of week on or after an exact day of month set the month to an exact month value day-of-month to the day on or after which the rule is applied and day-of-week to a DAY_OF_WEEK field value. For example to specify the second Sunday of April set month to APRIL day-of-month to 8 and day-of-week to SUNDAY}.- Day of week on or before day of month
To specify a day of the week on or before an exact day of the month set day-of-month and day-of-week to a negative value. For example to specify the last Wednesday on or before theLast day-of-week of month of-month to -1. For example to specify the last Sunday of October set month to OCTOBER day-of-week to SUNDAY and day-of-month to -1. The time of the day at which daylight saving time starts or ends is specified by a
To specify the last day-of-week of the month set day-of-week to a DAY_OF_WEEK value and day-backwardsmillisecond value within the day. There are three kinds of modes to specify the time: #WALL_TIME #STANDARD_TIME and #UTC_TIME For exampleDaylightif daylight saving time ends at 2:00 am in the wall clock time it can be specified by 7200000 milliseconds in the #WALL_TIME mode. In this case the wall clock time for an end-rule means the same thing as the daylight time.The
Savings Timefollowing are examples of parameters for constructing time zone objects.ends: at 2:00am in daylight time // on the last Sunday in October // Save: 1 hour SimpleTimeZone(// Base GMT offset: -8:00 // DST starts: at 2:00am in standard time // on the first Sunday in April // DST
dayOfWeekInMonth-28800000 "America/Los_Angeles" Calendar.APRIL 1 -Calendar.SUNDAY=7200000 Calendar.OCTOBER -1 Calendar.SUNDAY 7200000 3600000) // Base GMT offset: +1:00 // DST starts: at 1:00am in UTC time // on the last Sunday inOctoberMarchat//2DST ends:AMat 1:00am instandardUTC time // on the last Sunday in October // Save: 1 hour SimpleTimeZone(3600000 "Europe/Paris" Calendar.MARCH -1 Calendar.SUNDAY 3600000 SimpleTimeZone.UTC_TIME Calendar.OCTOBER -1 Calendar.SUNDAY 3600000 SimpleTimeZone.UTC_TIME 3600000) These parameter rules are also applicable to the set rule methods such assetStartRule
. @since 1.1 @see Calendar @see GregorianCalendar @see TimeZone @version 1.38 0143 12/1903/0001 @author David Goldsmith Mark Davis Chen-Lieh Huang Alan Liu
Constructs a SimpleTimeZone with the given base time zone offset from GMT and time zone IDClass SimpleTimeZone, constructor SimpleTimeZone(int, String, int, int, int, int, int, int, int, int). Timezone IDs can be obtained fromTimeZone.getAvailableIDs. Normally you should usewithTimeZone.getDefaultnoto construct a TimeZonedaylight saving time schedule. @param rawOffset Thegivenbase time zone offset in milliseconds to GMT. @param ID The time zoneID whichname that isobtainedgivenfromtoTimeZone.getAvailableIDsthis instance.
Class SimpleTimeZone, constructor SimpleTimeZone(int, String, int, int, int, int, int, int, int, int, int)ConstructConstructs a SimpleTimeZone with the given base time zone offset from GMT time zone IDtimeandtorulesstartfor starting andendending the daylight time.Timezone IDs can be obtained from TimeZone.getAvailableIDs.BothNormallystartTime
youandshouldendTime
useareTimeZone.getDefaultspecified tocreate 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 constructorbespecifiesrepresentedday-of-week-in-month rules. That is if the startDay is 1 and the startDayOfWeek is SUNDAY thenthis indicatesthefirst Sunday inwallthe startMonthclock time.AThestartDayamount of-1 likewise indicates the last Sunday. However by using negative or zero values for certain parameters otherdaylighttypes of rules cansaving is assumed to bespecified. Day of month. To specify an exact day of the month such as March 13600000set startDayOfWeek tomillisecondszero(i.Day of week after day of monthe.To specify the first day of the week occurring on or after an exact day of the month make the day of theoneweek negativehour).For example if startDay isThis5 and startDayOfWeekconstructor is-MONDAY this indicates the first Mondayequivalenton or after the 5thto:day@param rawOffset The given base time zone offset
ofSimpleTimeZone(rawOffsettheID startMonth. Day of week before day of month. To specify the last day of the week occurring onor before an exact day of the month make the day of the week and the day of the month negative. For example ifstartDayis -21 andstartDayOfWeekis -WEDNESDAY this indicates the last Wednesday on or before the 21st of thestartTimestartMonthSimpleTimeZone.The above examples refer to the startMonth startDay and startDayOfWeek;{@linkthe#WALL_TIME}same applies for theendMonth endDay endDayOfWeek endTimeendMonthSimpleTimeZone.{@linkendDay#WALL_TIME}and3600000)endDayOfWeek.tofrom GMT. @param ID The time zone ID which isobtainedgiven tofromthisTimeZone.getAvailableIDsobject. @param startMonth The daylightsavingssaving time starting month. Month is a MONTH field value (0-based.ege.g. 0 for January). @param startDay Thedaylight savings startingday of theday-of-week-in-month.on which the daylight savingPleasetime starts.seeSee thememberclass description foranthe specialexamplecases of this parameter. @param startDayOfWeek The daylightsavingssaving time starting day-of-week.Please seeSee thememberclass description foranthe special cases ofexamplethis parameter. @param startTime The daylightsavingssaving time starting time in local wall clock time (in milliseconds within the day) which is local standard time in this case.Please see the member description for an example.@param endMonth The daylightsavingssaving time ending month. Month is a MONTH field value (0-based.ege.g.09 forJanuaryOctober). @param endDay Thedaylight savings endingday of theday-of-week-in-month.on which the daylight saving timePleaseends.seeSee thememberclass description foranthe special cases of thisexampleparameter. @param endDayOfWeek The daylightsavingssaving time ending day-of-week.PleaseSeeseethememberclass description foranthe special casesexampleof this parameter. @param endTime The daylightsavingssaving ending time in local wall clock time (in milliseconds within the day) which is local daylight time in this case.Please see the member description for an example.@exception IllegalArgumentException if the month day dayOfWeek or time parameters are out of range for the start or end rule@since JDK1.1
Class SimpleTimeZone, Object clone()ConstructorConstructs a SimpleTimeZone with the given base time zone offset from GMT time zone ID and rules for starting and ending the daylight time. BothstartTime
andendTime
are assumed to be represented in the wall clock time. This constructor isidenticalequivalent to:@param rawOffset The given base time zone offset from GMT. @param ID The time zone ID which is given to this object. @param startMonth The daylight saving time starting month. Month is a MONTH field value (0-based. e.g. 0 for January). @param startDay The day of the month on which the daylight saving time starts. See the class description for theSimpleTimeZone(rawOffset ID startMonth startDay startDayOfWeek startTime SimpleTimeZone.{@link #WALL_TIME} endMonth endDay endDayOfWeek endTime SimpleTimeZone.{@link #WALL_TIME} dstSavings)
10special cases of this parameter. @param startDayOfWeek The daylight saving time starting day-of-argumentweek.constructorSee the class description for the special cases of this parameter. @param startTime The daylight saving time starting time in local wall clock time which is local standardbuttime in this case. @param endMonth Thealso takesdaylight saving time ending month. Month is adstSavingsMONTH field value (0-based. e.g. 9 for October). @param endDay The day of the month on which the daylight saving time ends. See the class description for the special cases of this parameter. @param endDayOfWeek The daylight saving time ending day-of-week. See the class description for the special cases of this parameter. @param endTime The daylight saving ending time in local wall clock time which is local daylight time in this case. @param dstSavings The amount of time inmsmilliseconds saved duringDSTdaylight saving time. @exception IllegalArgumentException if the month day dayOfWeek or time parameters are out of range for the start or end rule @since 1.2
Class SimpleTimeZone, boolean equals(Object)OverridesReturnsCloneablea clone of thisSimpleTimeZone
instance. @return a clone of this instance.
Compares the equality of twoClass SimpleTimeZone, int getDSTSavings()SimpleTimeZone
objects. @param obj TheSimpleTimeZone
object to be compared with. @return True if the givenobj
is the same as thisSimpleTimeZone
object; false otherwise.
Returns the amount of time inClass SimpleTimeZone, int getOffset(int, int, int, int, int, int)msmilliseconds that the clock is advanced duringDSTdaylight saving time. @return the number of milliseconds the time is advanced with respect to standard time when the daylightsavingssaving rules are in effect.A positiveor 0number(zero)typically one hourif this time(3600000)zone doesn't observe daylight saving time. @see #setDSTSavings @since 1.2
Returns the difference in milliseconds between local time and UTC taking into account both the raw offset and the effect of daylightClass SimpleTimeZone, int getRawOffset()savingssaving for the specified date and time. This method assumes that the start and end month are distinct. It also uses a default GregorianCalendar object as its underlying calendar such as for determining leap years. Do not use the result of this method with a calendar other than a defaultGregorianCalendar
.Note: In general clients should use
Calendar.get(ZONE_OFFSET) + Calendar.get(DST_OFFSET)
instead of calling this method. @param era The era of the given date. @param year The year in the given date. @param month The month in the given date. Month is 0-based. e.g. 0 for January. @param day The day-in-month of the given date. @param dayOfWeek The day-of-week of the given date. @param millis The milliseconds in day in standard local time. @return The milliseconds to add to UTC to get local time. @exception IllegalArgumentException theera
month
day
dayOfWeek
ormillis
parameters are out of range
Class SimpleTimeZone, boolean hasSameRules(TimeZone)Overrides TimeZoneGets the GMT offset for this time zone. @return the GMT offset value in milliseconds @see #setRawOffset
Class SimpleTimeZone, int hashCode()ReturnReturns true if this zone has the same rules and offset as another zone. @param other the TimeZone object to be compared with @return true if the given zone is a SimpleTimeZone and has the same rules and offset as this one @since 1.2
Class SimpleTimeZone, boolean inDaylightTime(Date)Override hashCode.Generates the hash code for the SimpleDateFormat object. @return the hash code for this object
Class SimpleTimeZone, void setDSTSavings(int)Overrides TimeZoneQueries if the given date is inDaylightdaylight saving time. @return true if daylight saving time is in effective at the given date;Savings Timefalse otherwise.
Sets the amount of time inClass SimpleTimeZone, void setEndRule(int, int, int)msmilliseconds that the clock is advanced duringDSTdaylight saving time. @param millisSavedDuringDST the number of milliseconds the time is advanced with respect to standard time when the daylightsavingssaving time rules are in effect. A positive number typically one hour (3600000). @see #getDSTSavings @since 1.2
Sets theClass SimpleTimeZone, void setEndRule(int, int, int, int)DSTdaylight saving time end rule to a fixed date within a month.@param month TheThismonth in whichmethod is equivalentthisto:rule@paramsetEndRule(endMonth
occursendDay(0-basedendTime).dayOfMonthendMonth Thedatedaylightinsavingthattime ending month. Month is a MONTH field value (10-based. e.g. 9 for October). @paramtimeendDay Thetimeday ofthat daythe(numbermonthof millis afteron which themidnight)daylightwhen DSTsaving time ends. @param endTime The daylight saving ending time in local wall clock time (in milliseconds within the day) which is local daylight time in this case. @exception IllegalArgumentException themonth dayOfMonthendMonth
endDay
ortimeendTime
parameters are out of range @since 1.2
Sets the daylightClass SimpleTimeZone, void setEndRule(int, int, int, int, boolean)savingssavingendingtime end rule. For exampleDaylightifSavingsdaylight savingTimetime endsaton the last(-1)Sunday in October at 2AMam instandardwall clock time.Thereforeyou can set the end rule by calling:setEndRule(
@paramTimeFieldsCalendar.OCTOBER -1TimeFieldsCalendar.SUNDAY 2*60*60*1000);monthendMonth The daylightsavingssaving time ending month. Month is a MONTH field value (0-based.ege.g.09 forJanuaryOctober). @paramdayOfWeekInMonthendDay Thedaylightdaysavings endingof theday-of-week-in-month.on which the daylight saving timePleaseends.seeSee thememberclass description forantheexamplespecial cases of this parameter. @paramdayOfWeekendDayOfWeek The daylightsavingssaving time ending day-of-week.Please seeSee thememberclass description foranthe specialexamplecases of this parameter. @paramtimeendTime The daylightsavingssaving ending time in local wall clock time (in milliseconds within the day) which is local daylight time in this case.Please see the member description for an example.@exception IllegalArgumentExceptionthe monthifdayOfWeekInMonththedayOfWeekendMonth
endDay
endDayOfWeek
ortimeendTime
parameters are out of range
Sets theClass SimpleTimeZone, void setRawOffset(int)DSTdaylight saving time end rule to a weekday before or aftera givethe given date within a month e.g. the first Monday on or after the 8th. @parammonthendMonth The daylight saving time ending month.in which thisMonth is aruleMONTH fieldoccursvalue (0-based).@param dayOfMonth A date withine.g.that month9 for(1-basedOctober). @paramdayOfWeekendDay The day of theweekmonth on whichthistheruledaylight saving timeoccursends. @paramtimeendDayOfWeek Thetime ofdaylightthat daysaving time(numberending day-of-week.millis@paramafterendTimemidnight)Thewhen DST endsdaylight saving ending time in local wall clock time (in milliseconds within the day) which is local daylight time in this case. @param after If true this rule selects the firstdayOfWeekendDayOfWeek
on or afterdayOfMonthendDay
. If false this rule selects the lastdayOfWeekendDayOfWeek
on or beforedayOfMonthendDay
of the month. @exception IllegalArgumentException themonth dayOfMonthendMonth
endDay
endDayOfWeek
dayOfWeekortimeendTime
parameters are out of range @since 1.2
Class SimpleTimeZone, void setStartRule(int, int, int)Overrides TimeZoneSets the base time zone offset to GMT. This is the offset to add*to*UTC to get local time.Please@seeTimeZone.setRawOffset for descriptions on the parameter.#getRawOffset
Sets theClass SimpleTimeZone, void setStartRule(int, int, int, int)DSTdaylight saving time start rule to a fixed date within a month.@param month TheThismonth in whichmethod is equivalentthisto:rule@paramsetStartRule(startMonth
occursstartDay(0-basedstartTime).dayOfMonthstartMonth Thedatedaylightinsaving timethatstarting month. Month is a MONTH field value (10-based. e.g. 0 for January). @paramtimestartDay Thetimeday ofthat daythe month(numberonofwhich themillis afterdaylight savingmidnight)timewhenstarts. @param startTime The daylight savingDST takes effecttime starting time in local wall clock time which is local standard time in this case. See the class description for the special cases of this parameter. @exception IllegalArgumentExceptionthe monthif thedayOfMonthstartMonth
startDayOfMonth
ortimestartTime
parameters are out of range @since 1.2
Sets the daylightClass SimpleTimeZone, void setStartRule(int, int, int, int, boolean)savingssavingstartingtime start rule. For exampleDaylightif daylightSavings Timesaving time startsaton the first Sunday in April at 2AMam instandardlocaltime.wall clockThereforetime you can set the start rule by calling:@paramsetStartRule(
TimeFieldsCalendar.APRIL 1TimeFieldsCalendar.SUNDAY 2*60*60*1000);monthstartMonth The daylightsavingssaving time starting month. Month is a MONTH field value (0-based.ege.g. 0 for January). @paramdayOfWeekInMonthstartDay Thedaylightdaysavings startingof theday-of-week-in-month.on which the daylight savingPleasetime starts.seeSee thememberclass description forantheexamplespecial cases of this parameter. @paramdayOfWeekstartDayOfWeek The daylightsavingssaving time starting day-of-week.Please seeSee thememberclass description forantheexamplespecial cases of this parameter. @paramtimestartTime The daylightsavingssaving time starting time in local wall clock time which is local standard time in this case.Please see the member description for an example.@exception IllegalArgumentExceptionthe monthifdayOfWeekInMonththedayOfWeekstartMonth
startDay
startDayOfWeek
ortimestartTime
parameters are out of range
Sets theClass SimpleTimeZone, void setStartYear(int)DSTdaylight saving time start rule to a weekday before or aftera givethe given date within a month e.g. the first Monday on or after the 8th. @parammonthstartMonth The daylight saving time starting month.in which thisMonth is aruleMONTHoccursfield value (0-based).@param dayOfMonth A date withine.g.that month0 for(1-basedJanuary). @paramdayOfWeekstartDay The day of theweekmonth on whichthistheruledaylight saving timeoccursstarts. @paramtimestartDayOfWeek Thetime ofdaylightthat daysaving time(numberstarting day-of-week.millis@paramafterstartTimemidnight)The daylightwhen DST takes effectsaving time starting time in local wall clock time which is local standard time in this case. @param after If true this rule selects the firstdayOfWeek
on or afterdayOfMonth
. If false this rule selects the lastdayOfWeek
on or beforedayOfMonth
. @exception IllegalArgumentExceptionthe monthifdayOfMonththedayOfWeekstartMonth
startDay
startDayOfWeek
ortimestartTime
parameters are out of range @since 1.2
Sets the daylightClass SimpleTimeZone, String toString()savingssaving time starting year. @param year The daylightsavingssaving starting year.
Class SimpleTimeZone, boolean useDaylightTime()ReturnReturns a string representation of this time zone. @return a string representation of this time zone.
Overrides TimeZoneQueries ifQueriesthis time zone uses daylight saving time. @return true if this time zone usesDaylightdaylight saving time;Savings Timefalse otherwise.
A map that further guarantees that it will be in ascending key order sorted according to the natural ordering of its keys (see the Comparable interface) or by a comparator provided at sorted map creation time. This order is reflected when iterating over the sorted map's collection views (returned by the entrySet keySet and values methods). Several additional operations are provided to take advantage of the ordering. (This interface is the map analogue of the SortedSet interface.)All keys inserted into a sorted map must implement the Comparable interface (or be accepted by the specified comparator). Furthermore all such keys must be mutually comparable: k1.compareTo(k2) (or comparator.compare(k1 k2)) must not throw a ClassCastException for any elements k1 and k2 in the sorted map. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException.
Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if the sorted map is to correctly implement the Map interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation but a sorted map performs all key comparisons using its compareTo (or compare) method so two keys that are deemed equal by this method are from the standpoint of the sorted map equal. The behavior of a tree map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.
All general-purpose sorted map implementation classes should provide four "standard" constructors: 1) A void (no arguments) constructor which creates an empty sorted map sorted according to the natural order of its keys. 2) A constructor with a single argument of type Comparator which creates an empty sorted map sorted according to the specified comparator. 3) A constructor with a single argument of type Map which creates a new map with the same key-value mappings as its argument sorted according to the keys' natural ordering. 4) A constructor with a single argument of type sorted map which creates a new sorted map with the same key-value mappings and the same ordering as the input sorted map. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but the SDK implementation (TreeMap) complies. @author Josh Bloch @version 1.
12 0213 12/0203/0001 @see Map @see TreeMap @see SortedSet @see Comparator @see Comparable @see Collection @see ClassCastException @since 1.2
A set that further guarantees that its iterator will traverse the set in ascending element order sorted according to the natural ordering of its elements (see Comparable) or by a Comparator provided at sorted set creation time. Several additional operations are provided to take advantage of the ordering. (This interface is the set analogue of SortedMap.)All elements inserted into an sorted set must implement the Comparable interface (or be accepted by the specified Comparator). Furthermore all such elements must be mutually comparable: e1.compareTo(e2) (or comparator.compare(e1 e2)) must not throw a ClassCastException for any elements e1 and e2 in the sorted set. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException.
Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation but a sorted set performs all element comparisons using its compareTo (or compare) method so two elements that are deemed equal by this method are from the standpoint of the sorted set equal. The behavior of a sorted set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.
All general-purpose sorted set implementation classes should provide four "standard" constructors: 1) A void (no arguments) constructor which creates an empty sorted set sorted according to the natural order of its elements. 2) A constructor with a single argument of type Comparator which creates an empty sorted set sorted according to the specified comparator. 3) A constructor with a single argument of type Collection which creates a new sorted set with the same elements as its argument sorted according to the elements' natural ordering. 4) A constructor with a single argument of type SortedSet which creates a new sorted set with the same elements and the same ordering as the input sorted set. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but the SDK implementation (the TreeSet class) complies. @author Josh Bloch @version 1.
15 0216 12/0203/0001 @see Set @see TreeSet @see SortedMap @see Collection @see Comparable @see Comparator @see java.lang.ClassCastException @since 1.2
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.
24 0225 12/0203/0001 @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 theStreamTokenizer
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 thereturnDelims
flag having the valuetrue
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 test25 0226 12/0203/0001 @see java.io.StreamTokenizer @since JDK1.0
Class TimeZone, Object clone()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 the U.S. Pacific Time zone is "America/Los_Angeles". So you can get a U.S. Pacific TimeTimeZone
object with:You can use theTimeZone tz = TimeZone.getTimeZone("America/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 thenyoua custom time zone ID cancreatebe specified to produce a TimeZone. The syntax of a custom time zone IDwithis:theHours must be between 0 to 23 and Minutes must be between 00 to 59. For examplefollowingCustomID:syntaxGMT
Sign Hours:
MinutesGMT
Sign Hours MinutesGMT
Sign Hours Sign: one of[+
|-]hh[[:]mm]Hours: Digit Digit Digit Minutes: Digit Digit Digit: one of0 1 2 3 4 5 6 7 8 9
you might"GMT+10"specifyand "GMT+14:000010"asmean ten hours and ten minutes ahead of GMT respectively.The format is locale independent and digits must be taken from the Basic Latin block of the Unicode standard. No daylight saving time transition schedule can be specified with
a custom time zone ID.TheIf the specified string doesn't match the syntax
TimeZone"GMT"thatisreturnedused.when you specifyWhen creating a
TimeZone
the specified custom time zone IDdoes not include daylight savingsis normalized in the followingtimesyntax:For example TimeZone.getTimeZone("GMT-8").getID() returns "GMT-08:00".NormalizedCustomID:GMT
Sign TwoDigitHours:
Minutes Sign: one of+ -
TwoDigitHours: Digit Digit Minutes: Digit Digit Digit: one of0 1 2 3 4 5 6 7 8 9
Three-letter time zone IDs
For compatibility with JDK 1.1.x some other three-letter time zone IDs (such as "PST" "CTT" "AST") are also supported. However their use is deprecated because the same abbreviation is often used for multiple time zones (for example "CST" could be U.S. "Central Standard Time" and "China Standard Time") and the Java platform can then only recognize one of them. @see Calendar @see GregorianCalendar @see SimpleTimeZone @version 1.56 0361 12/1803/01 @author Mark Davis David Goldsmith Chen-Lieh Huang Alan Liu @since JDK1.1
Class TimeZone, TimeZone getDefault()OverridesCreatesCloneablea copy of thisTimeZone
. @return a clone of thisTimeZone
Gets the defaultClass TimeZone, String getDisplayName()TimeZone
for this host. The source of the defaultTimeZone
may vary with implementation. @return a defaultTimeZone
. @see #setDefault
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 theClass TimeZone, String getDisplayName(Locale)formatnormalizedGMT[+-]hh:mmcustom ID format. @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. 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 theClass TimeZone, String getDisplayName(boolean, int)formatnormalizedGMT[+-]hh:mmcustom ID format. @param locale the locale in which to supply the display name. @return the human-readable name of this time zone in the given locale or in the default locale if the given locale is not recognized. @since 1.2
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 theClass TimeZone, String getDisplayName(boolean, int, Locale)formatnormalizedGMT[+-]hh:mmcustom ID format. @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 theClass TimeZone, int getOffset(int, int, int, int, int, int)formatnormalizedGMT[+-]hh:mmcustom ID format. @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 the time zone offset for current date modified in case of daylight savings. This is the offset to addClass TimeZone, int getRawOffset()*to*UTC to get local time.This method returns a historically correct offset if an underlying
TimeZone
implementation subclass supports historical Daylight Saving Time schedule and GMT offset changes. @param era the era of the given date. @param year the year in the given date. @param month the month in the given date. Month is 0-based. e.g. 0 for January. @param day the day-in-month of the given date. @param dayOfWeek the day-of-week of the given date. @param milliseconds themillismilliseconds in day in standard local time. @return the offset in milliseconds to add*to*GMT to get local time. @see Calendar#ZONE_OFFSET @see Calendar#DST_OFFSET
Class TimeZone, void setDefault(TimeZone)Gets unmodified offset NOT modifiedReturns the amount of time incasemillisecondsoftodaylightadd to UTC tosavingsget standard time in this time zone.ThisBecause this value is not affected by daylight saving time it is called raw offset.If an underlying
the method returns the raw offsetTimeZone
implementation subclass supports historical GMT offset changesto addvalue of*to*theUTCcurrent date. In Honolulu for example its raw offset changed from GMT-10:30 togetGMT-10:00localintime1947 and this method always returns -36000000 milliseconds (i.e. -10 hours). @return theunmodifiedamount of raw offsetto addtime in*milliseconds to*UTCadd togetUTC.local@seetime.Calendar#ZONE_OFFSET
Sets theClass TimeZone, void setRawOffset(int)TimeZone
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 @see #getDefault
Sets the base time zone offset to GMT. This is the offset to addClass TimeZone, boolean useDaylightTime()*to*UTC to get local time.If an underlying
TimeZone
implementation subclass supports historical GMT offset changes the specified GMT offset is set as the latest GMT offset and the difference from the known latest GMT offset value is used to adjust all historical GMT offset values. @param offsetMillis the given base time zone offset to GMT.
Queries if this time zone uses daylight savings time.If an underlying
TimeZone
implementation subclass supports historical Daylight Saving Time schedule changes the method refers to the latest Daylight Saving Time schedule information. @return true if this time zone uses daylight savings time false otherwise.
A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution or for repeated execution at regular intervals.Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks sequentially. Timer tasks should complete quickly. If a timer task takes excessive time to complete it "hogs" the timer's task execution thread. This can in turn delay the execution of subsequent tasks which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes.
After the last live reference to a Timer object goes away and all outstanding tasks have completed execution the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However this can take arbitrarily long to occur. By default the task execution thread does not run as a daemon thread so it is capable of keeping an application from terminating. If a caller wants to terminate a timer's task execution thread rapidly the caller should invoke the the timer's cancel method.
If the timer's task execution thread terminates unexpectedly for example because its stop method is invoked any further attempt to schedule a task on the timer will result in an IllegalStateException as if the timer's cancel method had been invoked.
This class is thread-safe: multiple threads can share a single Timer object without the need for external synchronization.
This class does not offer real-time guarantees: it schedules tasks using the Object.wait(long) method.
Implementation note: This class scales to large numbers of concurrently scheduled tasks (thousands should present no problem). Internally it uses a binary heap to represent its task queue so the cost to schedule a task is O(log n) where n is the number of concurrently scheduled tasks. @author Josh Bloch @version 1.
7 028 12/0203/0001 @see TimerTask @see Object#wait(long) @since 1.3
A task that can be scheduled for one-time or repeated execution by a Timer. @author Josh Bloch @version 1.6 027 12/0203/0001 @see Timer @since 1.3
The
TooManyListenersException
Exception is used as part of the Java Event model to annotate and implement a unicast special case of a multicast Event Source.The presence of a "throws TooManyListenersException" clause on any given concrete implementation of the normally multicast "void addXyzEventListener" event listener registration pattern is used to annotate that interface as implementing a unicast Listener special case that is that one and only one Listener may be registered on the particular event listener source concurrently.
@see java.util.EventObject @see java.util.EventListener @version 1.10 0011 01/0212/0203 @author Laurence P. G. Cable @since JDK1.1
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(Map)This implementation provides guaranteed log(n) time cost for the containsKey get put and remove operations. Algorithms are adaptations of those in Cormen Leiserson and Rivest's Introduction to Algorithms.
Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation but a map performs all key comparisons using its compareTo (or compare) method so two keys that are deemed equal by this method are from the standpoint of the sorted map equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.
Note that this implementation is not synchronized. If multiple threads access a map concurrently and at least one of the threads modifies the map structurally it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time to prevent accidental unsynchronized access to the map:
Map m = Collections.synchronizedMap(new TreeMap(...));The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created in any way except through the iterator's own remove or add methods the iterator throws a ConcurrentModificationException. Thus in the face of concurrent modification the iterator fails quickly and cleanly rather than risking arbitrary non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. @author Josh Bloch and Doug Lea @version 1.
43 0254 12/0203/0001 @see Map @see HashMap @see Hashtable @see Comparable @see Comparator @see Collection @see Collections#synchronizedMap(Map) @since 1.2
Constructs a new map containing the same mappings as the given map sorted according to the keys' natural order. All keys inserted into the new map must implement the Comparable interface. Furthermore all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any elements k1 and k2 in the map. This method runs in n*log(n) time. @param m the map whose mappings are to be placed in this map. @throws ClassCastException the keys in t are not Comparable or are not mutually comparable. @throws NullPointerException if the specified map is null.Class TreeMap, constructor TreeMap(SortedMap)
Constructs a new map containing the same mappings as the given SortedMap sorted according to the same ordering. This method runs in linear time. @param m the sorted map whose mappings are to be placed in this map and whose comparator is to be used to sort this map. @throws NullPointerException if the specified sorted map is null.Class TreeMap, boolean containsValue(Object)
Returns true if this map maps one or more keys to the specified value. More formally returns true if and only if this map contains at least one mapping to a value v such that (value==null v==null : value.equals(v)). This operation will probably require time linear in the Map size for most implementations of Map. @param value value whose presence in this Map is to be tested. @return true if a mapping to value exists; false otherwise. @since 1.2Class TreeMap, void putAll(Map)
Copies all of the mappings from the specified map to this map. These mappings replace any mappings that this map had for any of the keys currently in the specified map. @param map mappings to be stored in this map. @throws ClassCastException class of a key or value in the specified map prevents it from being stored in this map. @throws NullPointerException if the given map is null or this map does not permit null keys and a key in the specifiedClass TreeMap, Object remove(Object)keymap is null.
Removes the mapping for this key from this TreeMap if present. @param key key for which mapping should be removed @return previous value associated with specified key or null if there was no mapping for key. A null return can also indicate that the map previously associated null with the specified key. @throws ClassCastException key cannot be compared with the keys currently in the map. @throws NullPointerException key is null and this map uses natural order or its comparator does not tolerate null keys.
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(Collection)This implementation provides guaranteed log(n) time cost for the basic operations (add remove and contains).
Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation but a TreeSet instance performs all key comparisons using its compareTo (or compare) method so two keys that are deemed equal by this method are from the standpoint of the set equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.
Note that this implementation is not synchronized. If multiple threads access a set concurrently and at least one of the threads modifies the set it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time to prevent accidental unsynchronized access to the set:
SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));The Iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created in any way except through the iterator's own remove method the iterator will throw a ConcurrentModificationException. Thus in the face of concurrent modification the iterator fails quickly and cleanly rather than risking arbitrary non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. @author Josh Bloch @version 1.
20 0223 12/0203/0001 @see Collection @see Set @see HashSet @see Comparable @see Comparator @see Collections#synchronizedSortedSet(SortedSet) @see TreeMap @since 1.2
Constructs a new set containing the elements in the specified collection sorted according to the elements' natural order. All keys inserted into the set must implement the Comparable interface. Furthermore all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any elements k1 and k2 in the set. @param c The elements that will comprise the new set. @throws ClassCastException if the keys in theClass TreeSet, constructor TreeSet(Comparator)givenspecified collection are not comparable or are not mutually comparable. @throws NullPointerException if the specified collection is null.
Constructs a new empty set sorted according to theClass TreeSet, constructor TreeSet(SortedSet)givenspecified comparator. All elements inserted into the set must be mutually comparable by thegivenspecified 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.
Constructs a new set containing the same elements as theClass TreeSet, boolean addAll(Collection)givenspecified sorted set sorted according to the same ordering. @param s sorted set whose elements will comprise the new set. @throws NullPointerException if the specified sorted set is null.
Adds all of the elements in the specified collection to this set. @param c elements to be added @return true if this set changed as a result of the call. @throws ClassCastException if the elements provided cannot be compared with the elements currently in the set. @throws NullPointerException of the specified collection is null.Class TreeSet, SortedSet headSet(Object)
Returns a view of the portion of this set whose elements are strictly less than toElement. The returned sorted set is backed by this set so changes in the returned sorted set are reflected in this set and vice-versa. The returned sorted set supports all optional set operations.Class TreeSet, boolean remove(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 of a
givenspecified value merely request a headSet bounded by successor(highEndpoint). For example suppose that s is a sorted set of strings. The following idiom obtains a view containing all of the strings in s that are less than or equal to high:SortedSet head = s.headSet(high+"\0");@param toElement high endpoint (exclusive) of the headSet. @return a view of the portion of this set whose elements are strictly less than toElement. @throws ClassCastException if toElement is not compatible with this set's comparator (or if the set has no comparator if toElement does not implement Comparable). @throws IllegalArgumentException if this set is itself a subSet headSet or tailSet and toElement is not within the specified range of the subSet headSet or tailSet. @throws NullPointerException if toElement is null and this set uses natural ordering or its comparator does not tolerate null elements.
Removes theClass TreeSet, SortedSet subSet(Object, Object)givenspecified element from this set if it is present. @param o object to be removed from this set if present. @return true if the set contained the specified element. @throws ClassCastException if the specified object cannot be compared with the elements currently in the set.
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 of a
givenspecified value merely request the subrange from lowEndpoint to successor(highEndpoint). For example suppose that s is a sorted set of strings. The following idiom obtains a view containing all of the strings in s from low to high inclusive:SortedSet sub = s.subSet(low high+"\0");A similar technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the strings in s from low to high exclusive:SortedSet sub = s.subSet(low+"\0" high);@param fromElement low endpoint (inclusive) of the subSet. @param toElement high endpoint (exclusive) of the subSet. @return a view of the portion of this set whose elements range from fromElement inclusive to toElement exclusive. @throws ClassCastException if fromElement and toElement cannot be compared to one another using this set's comparator (or if the set has no comparator using natural ordering). @throws IllegalArgumentException if fromElement is greater than toElement. @throws NullPointerException if fromElement or toElement is null and this set uses natural order or its comparator does not tolerate null elements.
Returns a view of the portion of this set whose elements are greater than or equal to fromElement. The returned sorted set is backed by this set so changes in the returned sorted set are reflected in this set and vice-versa. The returned sorted set supports all optional set operations.The sorted set returned by this method will throw an IllegalArgumentException if the user attempts to insert an element less than fromElement. Note: this method always returns a view that contains its (low) endpoint. If you need a view that does not contain this endpoint and the element type allows for calculation of the successor of a
givenspecified value merely request a tailSet bounded by successor(lowEndpoint). For example suppose that s is a sorted set of strings. The following idiom obtains a view containing all of the strings in s that are strictly greater than low:SortedSet tail = s.tailSet(low+"\0");@param fromElement low endpoint (inclusive) of the tailSet. @return a view of the portion of this set whose elements are greater than or equal to fromElement. @throws ClassCastException if fromElement is not compatible with this set's comparator (or if the set has no comparator if fromElement does not implement Comparable). @throws IllegalArgumentException if this set is itself a subSet headSet or tailSet and fromElement is not within the specified range of the subSet headSet or tailSet. @throws NullPointerException if fromElement is null and this set uses natural ordering or its comparator does not tolerate null elements.
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 the Java 2 platform v1.2 this class has been retrofitted to implement List so that it becomes a part of Java's collection framework. Unlike the new collection implementations Vector is synchronized.
The Iterators returned by Vector's iterator and listIterator methods are fail-fast: if the Vector is structurally modified at any time after the Iterator is created in any way except through the Iterator's own remove or add methods the Iterator will throw a ConcurrentModificationException. Thus in the face of concurrent modification the Iterator fails quickly and cleanly rather than risking arbitrary non-deterministic behavior at an undetermined time in the future. The Enumerations returned by Vector's elements method are not fail-fast.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. @author Lee Boynton @author Jonathan Payne @version 1.
71 0485 12/1803/0001 @see Collection @see List @see ArrayList @see LinkedList @since JDK1.0
Constructs a vector containing the elements of the specified collection in the order they are returned by the collection's iterator. @param c the collection whose elements are to be placed into this vector. @throws NullPointerException if the specified collection is null. @since 1.2Class Vector, boolean addAll(Collection)
Appends all of the elements in the specified Collection to the end of this Vector in the order that they are returned by the specified Collection's Iterator. The behavior of this operation is undefined if the specified Collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified Collection is this Vector and this Vector is nonempty.) @param c elements to be inserted into this Vector. @return true if this Vector changed as a result of the call. @exception ArrayIndexOutOfBoundsException index out of range (index < 0 || index > size()). @throws NullPointerException if the specified collection is null. @since 1.2Class Vector, boolean addAll(int, Collection)
Inserts all of the elements in in the specified Collection into this Vector at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the Vector in the order that they are returned by the specified Collection's iterator. @param index index at which to insert first element from the specified collection. @param c elements to be inserted into this Vector. @return true if this Vector changed as a result of the call. @exception ArrayIndexOutOfBoundsException index out of range (index < 0 || index > size()). @throws NullPointerException if the specified collection is null. @since 1.2Class Vector, int capacity()
Returns the current capacity of this vector. @return the current capacity (the length of its internal dataClass Vector, boolean containsAll(Collection)araryarray kept in the field elementData of this vector).
Returns true if this Vector contains all of the elements in the specified Collection. @param c a collection whose elements will be tested for containment in this Vector @return true if this Vector contains all of the elements in the specified collection. @throws NullPointerException if the specified collection is null.Class Vector, void copyInto(Object[])
Copies the components of this vector into the specified array. The item at index k in this vector is copied into component k of anArray. The array must be big enough to hold all the objects in this vector else an IndexOutOfBoundsException is thrown. @param anArray the array into which the components get copied. @throws NullPointerException if the given array is null.Class Vector, Object get(int)
Returns the element at the specified position in this Vector. @param index index of element to return. @return object at the specified index @exception ArrayIndexOutOfBoundsException index is out of range (index < 0 || index >= size()). @since 1.2Class Vector, Object remove(int)
Removes the element at the specified position in this Vector. shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the Vector. @exception ArrayIndexOutOfBoundsException index out of range (index < 0 || index >= size()). @param index the index of the element to removed. @return element that was removed @since 1.2Class Vector, boolean removeAll(Collection)
Removes from this Vector all of its elements that are contained in the specified Collection. @param c a collection of elements to be removed from the Vector @return true if this Vector changed as a result of the call. @throws NullPointerException if the specified collection is null. @since 1.2Class Vector, boolean retainAll(Collection)
Retains only the elements in this Vector that are contained in the specified Collection. In other words removes from this Vector all of its elements that are not contained in the specified Collection. @param c a collection of elements to be retained in this Vector (all other elements are removed) @return true if this Vector changed as a result of the call. @throws NullPointerException if the specified collection is null. @since 1.2Class Vector, Object set(int, Object)
Replaces the element at the specified position in this Vector with the specified element. @param index index of element to replace. @param element element to be stored at the specified position. @return the element previously at the specified position. @exception ArrayIndexOutOfBoundsException index out of range (index < 0 || index >= size()). @Class Vector, Object[] toArray(Object[])exception IllegalArgumentException fromIndex > toIndex. @since 1.2
Returns an array containing all of the elements in this Vector in the correct orderClass Vector, void trimToSize(). The; the runtime type of the returned array is that of the specified array. If the Vector fits in the specified array it is returned therein. Otherwise a new array is allocated with the runtime type of the specified array and the size of this Vector.If the Vector fits in the specified array with room to spare (i.e. the array has more elements than the Vector) the element in the array immediately following the end of the Vector is set to null. This is useful in determining the length of the Vector only if the caller knows that the Vector does not contain any null elements. @param a the array into which the elements of the Vector are to be stored if it is big enough; otherwise a new array of the same runtime type is allocated for this purpose. @return an array containing the elements of the Vector. @exception ArrayStoreException the runtime type of a is not a supertype of the runtime type of every element in this Vector. @throws NullPointerException if the given array is null. @since 1.2
Trims the capacity of this vector to be the vector's current size. If the capacity of thiscectorvector is larger than its current size then the capacity is changed to equal the size by replacing its internal data array kept in the field elementData with a smaller one. An application can use this operation to minimize the storage of a vector.
A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector that is made finalizable finalized and then reclaimed. When a key has been discarded its entry is effectively removed from the map so this class behaves somewhat differently than other Map implementations.Class WeakHashMap, constructor WeakHashMap()Both null values and the null key are supported. This class has performance characteristics similar to those of the HashMap class and has the same efficiency parameters of initial capacity and load factor.
Like most collection classes this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap method.
This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated so it is impossible to do a lookup of that key in a WeakHashMap at some later time and be surprised that its entry has been removed. This class will work perfectly well with key objects whose equals methods are not based upon object identity such as String instances. With such recreatable key objects however the automatic removal of WeakHashMap entries whose keys have been discarded may prove to be confusing.
The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods it is possible for the size method to return smaller values over time for the isEmpty method to return false and then true for the containsKey method to return true and later false for a given key for the get method to return a value for a given key but later return null for the put method to return null and the remove method to return false for a key that previously appeared to be in the map and for successive examinations of the key set the value set and the entry set to yield successively smaller numbers of elements.
Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. Therefore a key will automatically be removed only after the weak references to it both inside and outside of the map have been cleared by the garbage collector.
Implementation note: The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys either directly or indirectly since that will prevent the keys from being discarded. Note that a value object may refer indirectly to its key via the WeakHashMap itself; that is a value object may strongly refer to some other key object whose associated value object in turn strongly refers to the key of the first value object.
This problem mayOne way tobedeal with this is to wrap values themselves within WeakReferences before inserting as in: m.put(key new WeakReference(value)) and then unwrapping upon each get.The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is
fixedcreated in any way except through the iterator's own remove or add methods the iterator will throw a ConcurrentModificationException. Thus in the face of concurrent modification the iterator fails quickly and cleanly rather than risking arbitrary non-deterministic behavior at an undetermined time in the future.Note that the fail-fast behavior of an iterator cannot be guaranteed as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast
releaseiterators throw ConcurrentModificationException on a best-effort basis. Therefore it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. @version 1.12 0219 12/0203/0001 @author Doug Lea @author Josh Bloch @author Mark Reinhold @since 1.2 @see java.util.HashMap @see java.lang.ref.WeakReference
Constructs a new empty WeakHashMap with the default initial capacity (16) and the default load factorClass WeakHashMap, constructor WeakHashMap(Map)which is(0.75).
Constructs a new WeakHashMap with the same mappings as the specified Map. The WeakHashMap is created withClass WeakHashMap, constructor WeakHashMap(int)an initial capacity of twice the number ofdefaultmappings in the specifiedload factor which ismap0.75or 11and an(whicheverinitialiscapacitygreater)sufficientand a default load factor which isto hold the mappings in the specified0.75Map. @param t the map whose mappings are to be placed in this map. @throws NullPointerException if the specified map is null. @since 1.3
Constructs a new empty WeakHashMap with the given initial capacity and the default load factor which is 0.75. @param initialCapacity The initial capacity of the WeakHashMap @throws IllegalArgumentException If the initial capacity isClass WeakHashMap, constructor WeakHashMap(int, float)less than zeronegative.
Constructs a new empty WeakHashMap with the given initial capacity and the given load factor. @param initialCapacity The initial capacity of the WeakHashMap @param loadFactor The load factor of the WeakHashMap @throws IllegalArgumentException If the initial capacity isClass WeakHashMap, boolean containsKey(Object)lessnegativethan zeroor if the load factor is nonpositive.
Returns true if this map contains a mapping for the specified key. @param key The key whose presence in this map is to be tested @return true if there is a mapping for key; false otherwiseClass WeakHashMap, boolean containsValue(Object)
Returns true if this map maps one or more keys toClass WeakHashMap, Set entrySet()this value. More formally returns true if and only if this map contains at least one mapping to a value v such that (value==null v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations of map. This implementation iterates over entrySet() searching for an entry withthe specified value.If such an entry is found true is returned. If the iteration terminates without finding such an entry false is returned. Note that this implementation requires linear time in the size of the map.@param value value whose presence in this map is to be tested. @return true if this map maps one or more keys tothisthe specified value.
Returns aClass WeakHashMap, Object get(Object)Setcollection view of the mappings contained in this map. Each element in the returned collection is a Map.Entry. The collection is backed by the map so changes to the map are reflected in the collection and vice-versa. The collection supports element removal which removes the corresponding mapping from the map via the Iterator.remove Collection.remove removeAll retainAll and clear operations. It does not support the add or addAll operations. @return a collection view of the mappings contained in this map. @see Map.Entry
Returns the value to which the specified key is mapped in this weak hash mapClass WeakHashMap, boolean isEmpty()mapsor null if thespecifiedmap contains no mapping for this key.If thisA returnmapvalue of null does notcontainnecessarilyaindicatevaluethat the map contains no mapping forthisthe key;thenitreturnis also possible that the map explicitly maps the key to null. The containsKey method may be used to distinguish these two cases. @param keyThethe key whose associated valueif anyis to be returned. @return the value to which this map maps the specified key or null if the map contains no mapping for this key. @see #put(Object Object)
Returns true if this map contains no key-value mappings. This result is a snapshot and may not reflect unprocessed entries that will be removed before next attempted access because they are no longer referenced.Class WeakHashMap, Set keySet()
Returns aClass WeakHashMap, Object put(Object, Object)Setset view of the keys contained in this map. TheSetset is backed by the map so changes to the map are reflected in theSetset and vice-versa.(If the map is modified while an iteration over the Set is in progress the results of the iteration are undefined.)TheSetset supports element removal which removes the correspondingentrymapping fromthethis map via the Iterator.remove Set.remove removeAll retainAll and clear operations. It does not support the add or addAll operations.This implementation returns a Set that subclasses AbstractSet. The subclass's iterator method returns a "wrapper object" over this map's entrySet() iterator. The size method delegates to this map's size method and the contains method delegates to this map's containsKey method. The Set is created the first time this method is called and returned in response to all subsequent calls. No synchronization is performed so there is a slight chance that multiple calls to this method will not all return the same Set.@return aSetset view of the keys contained in this map.
Class WeakHashMap, void putAll(Map)Updates this map so thatAssociates the specified value with thegivenspecified keymapsto theingiventhisvaluemap. If the map previously contained a mapping forkey then that mapping is replacedthisandkey thepreviousold value isreturnedreplaced. @param keyThekeythat is to be mapped to the givenwith which the specified value is to bevalueassociated. @param valueThevalue towhich the givenbekeyassociatedis to bewith the specifiedmappedkey. @returnTheprevious valueto which thisassociated with specified keywas mappedor null ififthere was no mapping for key. A null return can also indicate that the HashMap previously associated null with the specified key.
Copies all of the mappings from the specified map to this mapClass WeakHashMap, Object remove(Object)(optional operation).These mappings will replace any mappings that this map had for any of the keys currently in the specified map.
This implementation iterates over the specified map's entrySet() collection and calls this map's put operation once for each entry returned by the iteration.@param t mappings to be stored in this map. @throwsUnsupportedOperationException if the putAll operation is not supported by this map. @throws ClassCastException if the class of a key or value in the specified map prevents it from being stored in this map. @throws IllegalArgumentExceptionNullPointerException ifsome aspect of a key or value inthe specified mapprevents it from being stored in this map. @throws NullPointerException this map does not permit null keys or values and the specified key or valueis null.
Removes the mapping forClass WeakHashMap, int size()the giventhis key from this map if present. @param keyThekey whose mapping is to be removed from the map. @returnTheprevious valuetoassociatedwhich thiswith specified keywas mappedor null if there was no mapping for key. A null return can also indicate that the map previously associated null with the specified key.
Returns the number of key-value mappings in this map.Class WeakHashMap, Collection values()Note:ThisInresultcontrast with most implementations of theis a snapshot and may notMapreflectinterface the time required by this operation is linear in the size of theunprocessed entries that will be removed before next attempted access because they are nomaplonger referenced.
Returns a collection view of the values contained in this map. The collection is backed by the map so changes to the map are reflected in the collection and vice-versa.(If the map is modified while an iteration over the collection is in progress the results of the iteration are undefined.)The collection supports element removal which removes the correspondingentrymapping fromthethis map via the Iterator.remove Collection.remove removeAll retainAll and clear operations. It does not support the add or addAll operations.This implementation returns a collection that subclasses abstract collection. The subclass's iterator method returns a "wrapper object" over this map's entrySet() iterator. The size method delegates to this map's size method and the contains method delegates to this map's containsValue method. The collection is created the first time this method is called and returned in response to all subsequent calls. No synchronization is performed so there is a slight chance that multiple calls to this method will not all return the same Collection.@return a collection view of the values contained in this map.