|
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 contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.Class Arrays, void sort(Object[])The methods in this class all throw a NullPointerException if the specified array reference 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.
44 1245 02/0312/0102 @see Comparable @see Comparator @since 1.2
Sorts the specified array of objects into ascending order according to the natural ordering of its elements. All elements in the array must implement the Comparable interface. Furthermore all elements in the array must be mutually comparable (that is e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).Class Arrays, void sort(Object[], Comparator)This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance
and can approach linear performance on nearly sorted lists. @param a the array to be sorted. @throws ClassCastException if the array contains elements that are not mutually comparable (for example strings and integers). @see Comparable
Sorts the specified array of objects according to the order induced by the specified comparator. All elements in the array must be mutually comparable by the specified comparator (that is c.compare(e1 e2) must not throw a ClassCastException for any elements e1 and e2 in the array).Class Arrays, void sort(Object[], int, int)This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance
and can approach linear performance on nearly sorted lists. @param a the array to be sorted. @param c the comparator to determine the order of the array. A null value indicates that the elements' natural ordering should be used. @throws ClassCastException if the array contains elements that are not mutually comparable using the specified comparator. @see Comparator
Sorts the specified range of the specified array of objects into ascending order according to the natural ordering of its elements. The range to be sorted extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be sorted is empty.) All elements in this range must implement the Comparable interface. Furthermore all elements in this range must be mutually comparable (that is e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).Class Arrays, void sort(Object[], int, int, Comparator)This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance
and can approach linear performance on nearly sorted lists. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length @throws ClassCastException if the array contains elements that are not mutually comparable (for example strings and integers). @see Comparable
Sorts the specified range of the specified array of objects according to the order induced by the specified comparator. The range to be sorted extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be sorted is empty.) All elements in the range must be mutually comparable by the specified comparator (that is c.compare(e1 e2) must not throw a ClassCastException for any elements e1 and e2 in the range).This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance
and can approach linear performance on nearly sorted lists. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @param c the comparator to determine the order of the array. A null value indicates that the elements' natural ordering should be used. @throws ClassCastException if the array contains elements that are not mutually comparable using the specified comparator. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length @see Comparator
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 aCalendar
object whose time fields have been initialized with the current date and time:Calendar rightNow = Calendar.getInstance();A
Calendar
object can produce all the time field values needed to implement the date-time formatting for a particular language and calendar style (for example Japanese-Gregorian Japanese-Traditional).Calendar
defines the range of values returned by certain fields as well as their meaning. For example the first month of the year has 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 historical 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:
- 23:59 is the last minute of the day and 00:00 is the first minute of the next day. Thus 23:59 on Dec 31 1999 < 00:00 on Jan 1 2000 < 00:01 on Jan 1 2000.
- 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: See int)
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.69 1270 01/0322/0102 @author Mark Davis David Goldsmith Chen-Lieh Huang Alan Liu @since JDK1.1
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, void sort(List)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.
59 1263 05/0312/0102 @see Collection @see Set @see List @see Map @since 1.2
Sorts the specified list into ascending order according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore all elements in the list must be mutually comparable (that is e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).Class Collections, void sort(List, Comparator)This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The specified list must be modifiable but need not be resizable.
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance
and can approach linear performance on nearly sorted lists. This implementation dumps the specified list into an array sorts the array and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place. @param list the list to be sorted. @throws ClassCastException if the list contains elements that are not mutually comparable (for example strings and integers). @throws UnsupportedOperationException if the specified list's list-iterator does not support the set operation. @see Comparable
Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is c.compare(e1 e2) must not throw a ClassCastException for any elements e1 and e2 in the list).This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance
and can approach linear performance on nearly sorted lists. The specified list must be modifiable but need not be resizable. This implementation dumps the specified list into an array sorts the array and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place. @param list the list to be sorted. @param c the comparator to determine the order of the list. A null value indicates that the elements' natural ordering should be used. @throws ClassCastException if the list contains elements that are not mutually comparable using the specified comparator. @throws UnsupportedOperationException if the specified list's list-iterator does not support the set operation. @see Comparator
The classDate
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
formfrom 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.
71721202/0312/0102 @see java.text.DateFormat @see java.util.Calendar @see java.util.TimeZone @since JDK1.0
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 0 to 6. 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 hours6669 @author David Goldsmith Mark Davis Chen-Lieh Huang Alan Liu @since JDK1.1
Hash table based implementation of the Map interface. This implementation provides all of the optional map operations and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular it does not guarantee that the order will remain constant over time.This implementation provides constant-time performance for the basic operations (get and put) assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus it's very important not to set the initial 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.
51 0152 04/2420/02 @see Object#hashCode() @see Collection @see Map @see TreeMap @see Hashtable @since 1.2
This class implements a hashtable which maps keys to values. Any non-Class Hashtable, boolean containsKey(Object)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.
90 1291 04/1321/0102 @see Object#equals(java.lang.Object) @see Object#hashCode() @see Hashtable#rehash() @see Collection @see Map @see HashMap @see TreeMap @since JDK1.0
Tests if the specified object is a key in this hashtable. @param key possible key. @returnClass Hashtable, boolean containsValue(Object)true
if and only if the specified object is a key in this hashtable as determined by the equals method;false
otherwise. @throws NullPointerException if the key isnull
. @see #contains(Object)
Returns true if this Hashtable maps one or more keys to this value.Class Hashtable, Object get(Object)Note that this method is identical in functionality to contains (which predates the Map interface). @param value value whose presence in this Hashtable is to be tested. @return true if this map maps one or more keys to the specified value. @throws NullPointerException if the value is
null
. @see Map @since 1.2
Returns the value to which the specified key is mapped in this hashtable. @param key a key in the hashtable. @return the value to which the key is mapped in this hashtable;Class Hashtable, Object remove(Object)null
if the key is not mapped to any value in this hashtable. @throws NullPointerException if the key isnull
. @see #put(Object Object)
Removes the key (and its corresponding value) from this hashtable. This method does nothing if the key is not in the hashtable. @param key the key that needs to be removed. @return the value to which the key had been mapped in this hashtable ornull
if the key did not have a mapping. @throws NullPointerException if the key isnull
.
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 containsAll(Collection)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.
36 1237 04/0311/0102 @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
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)
TheProperties
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.64 06/26/00 @since JDK1.0
An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed which is modified using a linear congruential formula. (See Donald Knuth The Art of Computer Programming Volume 2 Section 3.2.1.)If two instances of
Random
are created with the same seed and the same sequence of method calls is made for each they will generate and return identical sequences of numbers. In order to guarantee this property particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random for the sake of absolute portability of Java code. However subclasses of class Random are permitted to use other algorithms so long as they adhere to the general contracts for all the methods.The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.
Many applications will find the
random
method in classMath
simpler to use. @author Frank Yellin @version 1.3738 03/0604/02 @see java.lang.Math#random() @since JDK1.0
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 then a custom time zone ID can be specified to produce a TimeZone. The syntax of a custom time zone ID is:Hours must be between 0 to 23 and Minutes must be between 00 to 59. For example "GMT+10" and "GMT+0010" mean ten hours and ten minutes ahead of GMT respectively.CustomID:GMT
Sign Hours:
MinutesGMT
Sign Hours MinutesGMT
Sign Hours Sign: one of+ -
Hours: Digit Digit Digit Minutes: Digit Digit Digit: one of0 1 2 3 4 5 6 7 8 9
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. If the specified string doesn't match the syntax
"GMT"
is used.When creating a
TimeZone
the specified custom time zone ID is normalized in the following syntax: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.61 1262 01/0321/0102 @author Mark Davis David Goldsmith Chen-Lieh Huang Alan Liu @since JDK1.1
A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector that is made finalizable finalized and then reclaimed. When a key has been discarded its entry is effectively removed from the map so this class behaves somewhat differently than other Map implementations.Both null values and the null key are supported. This class has performance characteristics similar to those of the HashMap class and has the same efficiency parameters of initial capacity and load factor.
Like most collection classes this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap method.
This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated so it is impossible to do a lookup of that key in a WeakHashMap at some later time and be surprised that its entry has been removed. This class will work perfectly well with key objects whose equals methods are not based upon object identity such as String instances. With such recreatable key objects however the automatic removal of WeakHashMap entries whose keys have been discarded may prove to be confusing.
The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods it is possible for the size method to return smaller values over time for the isEmpty method to return false and then true for the containsKey method to return true and later false for a given key for the get method to return a value for a given key but later return null for the put method to return null and the remove method to return false for a key that previously appeared to be in the map and for successive examinations of the key set the value set and the entry set to yield successively smaller numbers of elements.
Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. Therefore a key will automatically be removed only after the weak references to it both inside and outside of the map have been cleared by the garbage collector.
Implementation note: The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys either directly or indirectly since that will prevent the keys from being discarded. Note that a value object may refer indirectly to its key via the WeakHashMap itself; that is a value object may strongly refer to some other key object whose associated value object in turn strongly refers to the key of the first value object. One way to deal 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 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. @version 1.
19 1220 04/0320/0102 @author Doug Lea @author Josh Bloch @author Mark Reinhold @since 1.2 @see java.util.HashMap @see java.lang.ref.WeakReference