Generated by
JDiff

java.util Documentation Differences

This file contains all the changes in documentation in the package java.util as colored differences. Deletions are shown like this, and additions are shown like this.
If no deletions or additions are shown in an entry, the HTML tags will be what has changed. The new HTML tags are shown in the differences. If no documentation existed, and then some was added in a later version, this change is noted in the appropriate class pages of differences, but the change is not shown on this page. Only changes in existing text are shown here. Similarly, documentation which was inherited from another class or interface is not shown here.
Note that an HTML error in the new documentation may cause the display of other documentation changes to be presented incorrectly. For instance, failure to close a <code> tag will cause all subsequent paragraphs to be displayed differently.

Class Arrays

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.

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

Class Arrays, void sort(Object[])

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

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

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

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

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

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

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

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

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

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance and can approach linear performance on nearly sorted lists. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length @throws ClassCastException if the array contains elements that are not mutually comparable (for example strings and integers). @see Comparable

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

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

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

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


Class Calendar

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

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

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

 Calendar rightNow = Calendar.getInstance(); 

A Calendar object can produce all the time field values needed to implement the date-time formatting for a particular language and calendar style (for example Japanese-Gregorian Japanese-Traditional). Calendar defines the range of values returned by certain fields as well as their meaning. For example the first month of the year has value MONTH == JANUARY for all calendars. Other values are defined by the concrete subclass such as ERA and YEAR. See individual field documentation and subclass documentation for details.

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

Calendar defines a locale-specific seven day week using two parameters: the first day of the week and the minimal days in first week (from 1 to 7). These numbers are taken from the locale resource data when a Calendar is constructed. They may also be specified explicitly through the API.

When setting or getting the WEEK_OF_MONTH or WEEK_OF_YEAR fields Calendar must determine the first week of the month or year as a reference point. The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least getMinimalDaysInFirstWeek() days of that month or year. Weeks numbered ... -1 0 precede the first week; weeks numbered 2 3 ... follow it. Note that the normalized numbering returned by get() may be different. For example a specific Calendar subclass may designate the week before week 1 of a year as week n of the previous year.

When computing a Date from time fields two special circumstances may arise: there may be insufficient information to compute the Date (such as only year and month but no day in the month) or there may be inconsistent information (such as "Tuesday July 15 1996" -- July 15 1996 is actually a Monday).

Insufficient information. The calendar will use default information to specify the missing fields. This may vary by calendar; for the Gregorian calendar the default for a field is the same as that of the start of the epoch: i.e. YEAR = 1970 MONTH = JANUARY DATE = 1 etc.

Inconsistent information. If fields conflict the calendar will give preference to fields set more recently. For example when determining the day the calendar will look for one of the following combinations of fields. The most recent combination as determined by the most recently set single field will be used.

 MONTH + DAY_OF_MONTH MONTH + WEEK_OF_MONTH + DAY_OF_WEEK MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK DAY_OF_YEAR DAY_OF_WEEK + WEEK_OF_YEAR 
For the time of day:
 HOUR_OF_DAY AM_PM + HOUR 

Note: for some non-Gregorian calendars different fields may be necessary for complete disambiguation. For example a full specification of the 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:

  1. 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.
  2. Although historically not precise midnight also belongs to "am" and noon belongs to "pm" so on the same day 12:00 am (midnight) < 12:01 am and 12:00 pm (noon) < 12:01 pm

The date or time format strings are not part of the definition of a calendar as those must be modifiable or overridable by the user at runtime. Use DateFormat to format dates.

Field manipulation methods

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

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

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

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

Add rule 1. The value of field f after the call minus the value of field f before the call is delta modulo any overflow that has occurred in field f. Overflow occurs when a field value exceeds its range and as a result the next larger field is incremented or decremented and the field value is adjusted back into its range.

Add rule 2. If a smaller field is expected to be invariant but   it is impossible for it to be equal to its prior value because of changes in its minimum or maximum after field f is changed then its value is adjusted to be as close as possible to its expected value. A smaller field represents a smaller unit of time. HOUR is a smaller field than DAY_OF_MONTH. No adjustment is made to smaller fields that are not expected to be invariant. The calendar system determines what fields are expected to be invariant.

In addition unlike set() add() forces an immediate recomputation of the calendar's milliseconds and all fields.

Example: Consider a GregorianCalendar originally set to August 31 1999. Calling add(Calendar.MONTH 13) sets the calendar to September 30 2000. Add rule 1 sets the MONTH field to September since adding 13 months to August gives September of the next year. Since DAY_OF_MONTH cannot be 31 in September in a GregorianCalendar add rule 2 sets the DAY_OF_MONTH to 30 the closest possible value. Although it is a smaller field DAY_OF_WEEK is not adjusted by rule 2 since it is expected to change when the month changes in a GregorianCalendar.

roll(f delta) adds delta to field f without changing larger fields. This is equivalent to calling add(f delta) with the following adjustment:

Roll rule. Larger fields are unchanged after the call. A larger field represents a larger unit of time. DAY_OF_MONTH is a larger field than HOUR.

Example: See int)

Usage model. To motivate the behavior of add() and roll() consider a user interface component with increment and decrement buttons for the month day and year and an underlying GregorianCalendar. If the interface reads January 31 1999 and the user presses the month increment button what should it read If the underlying implementation uses set() it might read March 3 1999. A better result would be February 28 1999. Furthermore if the user presses the month increment button again it should read March 31 1999 not March 28 1999. By saving the original date and using either add() or roll() depending on whether larger fields should be affected the user interface can behave as most users will intuitively expect.

@see Date @see GregorianCalendar @see TimeZone @see java.text.DateFormat @version 1.69 1270 01/0322/0102 @author Mark Davis David Goldsmith Chen-Lieh Huang Alan Liu @since JDK1.1

Class Collections

This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections "wrappers" which return a new collection backed by a specified collection and a few other odds and ends.

The methods of this class all throw a NullPointerException if the collections provided to them are null.

The documentation for the polymorphic algorithms contained in this class generally includes a brief description of the implementation. Such descriptions should be regarded as implementation notes rather than parts of the specification. Implementors should feel free to substitute other algorithms so long as the specification itself is adhered to. (For example the algorithm used by sort does not have to be a mergesort but it does have to be stable.)

The "destructive" algorithms contained in this class that is the algorithms that modify the collection on which they operate are specified to throw UnsupportedOperationException if the collection does not support the appropriate mutation primitive(s) such as the set method. These algorithms may but are not required to throw this exception if an invocation would have no effect on the collection. For example invoking the sort method on an unmodifiable list that is already sorted may or may not throw UnsupportedOperationException. @author Josh Bloch @version 1.59 1263 05/0312/0102 @see Collection @see Set @see List @see Map @since 1.2

Class Collections, void sort(List)

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

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

Class Collections, void sort(List, Comparator)

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

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

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance and can approach linear performance on nearly sorted lists. The specified list must be modifiable but need not be resizable. This implementation dumps the specified list into an array sorts the array and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place. @param list the list to be sorted. @param c the comparator to determine the order of the 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


Class Date

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

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

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

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

 http://tycho.usno.navy.mil 

and their definitions of "Systems of Time" at:

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

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

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


Class GregorianCalendar

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

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

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

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

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

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

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

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

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

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

Example:

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

Class HashMap

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

This implementation provides constant-time performance for the basic operations (get and put) assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus it's very important not to set the 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


Class Hashtable

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

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

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

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

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

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

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

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

To retrieve a number use the following code:

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

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

The Iterators returned by the iterator and listIterator methods of the Collections returned by all of Hashtable's "collection view methods" are fail-fast: if the Hashtable is structurally modified at any time after the Iterator is created in any way except through the Iterator's own remove or add methods the Iterator will throw a ConcurrentModificationException. Thus in the face of concurrent modification the Iterator fails quickly and cleanly rather than risking arbitrary non-deterministic behavior at an undetermined time in the future. The Enumerations returned by Hashtable's keys and values methods are not fail-fast.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. @author Arthur van Hoff @author Josh Bloch @version 1.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

Class Hashtable, boolean containsKey(Object)

Tests if the specified object is a key in this hashtable. @param key possible key. @return 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 is null. @see #contains(Object)
Class Hashtable, boolean containsValue(Object)

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

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

Class Hashtable, Object get(Object)

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; null if the key is not mapped to any value in this hashtable. @throws NullPointerException if the key is null. @see #put(Object Object)
Class Hashtable, Object remove(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 or null if the key did not have a mapping. @throws NullPointerException if the key is null.

Class List

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

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

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

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

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

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

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

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

Some list implementations have restrictions on the elements that they may contain. For example some implementations prohibit null elements and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface. @author Josh Bloch @version 1.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

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 Properties

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

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

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

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


Class Random

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

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

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

Many applications will find the random method in class Math simpler to use. @author Frank Yellin @version 1.3738 03/0604/02 @see java.lang.Math#random() @since JDK1.0


Class TimeZone

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

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

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

 TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles"); 
You can use the getAvailableIDs method to iterate through all the supported time zone IDs. You can then choose a supported ID to get a TimeZone. If the time zone you want is not represented by one of the supported IDs then a custom time zone ID can be specified to produce a TimeZone. The syntax of a custom time zone ID is:
 CustomID: GMT Sign Hours : Minutes GMT Sign Hours Minutes GMT Sign Hours Sign: one of + - Hours: Digit Digit Digit Minutes: Digit Digit Digit: one of 0 1 2 3 4 5 6 7 8 9 
Hours must be between 0 to 23 and Minutes must be between 00 to 59. For example "GMT+10" and "GMT+0010" mean 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. 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:

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

Three-letter time zone IDs

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

Class WeakHashMap

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

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

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

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

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

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

Implementation note: The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys either directly or indirectly since that will prevent the keys from being discarded. Note that a value object may refer indirectly to its key via the WeakHashMap itself; that is a value object may strongly refer to some other key object whose associated value object in turn strongly refers to the key of the first value object. 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