1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.  Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 */
26
27/*
28 * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved
29 * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
30 *
31 *   The original version of this source code and documentation is copyrighted
32 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
33 * materials are provided under terms of a License Agreement between Taligent
34 * and Sun. This technology is protected by multiple US and International
35 * patents. This notice and attribution to Taligent may not be removed.
36 *   Taligent is a registered trademark of Taligent, Inc.
37 *
38 */
39
40package java.util;
41
42import java.io.IOException;
43import java.io.ObjectInputStream;
44import java.io.ObjectOutputStream;
45import java.io.OptionalDataException;
46import java.io.Serializable;
47import java.security.AccessControlContext;
48import java.security.AccessController;
49import java.security.PermissionCollection;
50import java.security.PrivilegedActionException;
51import java.security.PrivilegedExceptionAction;
52import java.security.ProtectionDomain;
53import java.text.DateFormat;
54import java.text.DateFormatSymbols;
55import java.util.concurrent.ConcurrentHashMap;
56import java.util.concurrent.ConcurrentMap;
57import libcore.icu.LocaleData;
58
59/**
60 * The <code>Calendar</code> class is an abstract class that provides methods
61 * for converting between a specific instant in time and a set of {@link
62 * #fields calendar fields} such as <code>YEAR</code>, <code>MONTH</code>,
63 * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, and so on, and for
64 * manipulating the calendar fields, such as getting the date of the next
65 * week. An instant in time can be represented by a millisecond value that is
66 * an offset from the <a name="Epoch"><em>Epoch</em></a>, January 1, 1970
67 * 00:00:00.000 GMT (Gregorian).
68 *
69 * <p>The class also provides additional fields and methods for
70 * implementing a concrete calendar system outside the package. Those
71 * fields and methods are defined as <code>protected</code>.
72 *
73 * <p>
74 * Like other locale-sensitive classes, <code>Calendar</code> provides a
75 * class method, <code>getInstance</code>, for getting a generally useful
76 * object of this type. <code>Calendar</code>'s <code>getInstance</code> method
77 * returns a <code>Calendar</code> object whose
78 * calendar fields have been initialized with the current date and time:
79 * <blockquote>
80 * <pre>
81 *     Calendar rightNow = Calendar.getInstance();
82 * </pre>
83 * </blockquote>
84 *
85 * <p>A <code>Calendar</code> object can produce all the calendar field values
86 * needed to implement the date-time formatting for a particular language and
87 * calendar style (for example, Japanese-Gregorian, Japanese-Traditional).
88 * <code>Calendar</code> defines the range of values returned by
89 * certain calendar fields, as well as their meaning.  For example,
90 * the first month of the calendar system has value <code>MONTH ==
91 * JANUARY</code> for all calendars.  Other values are defined by the
92 * concrete subclass, such as <code>ERA</code>.  See individual field
93 * documentation and subclass documentation for details.
94 *
95 * <h4>Getting and Setting Calendar Field Values</h4>
96 *
97 * <p>The calendar field values can be set by calling the <code>set</code>
98 * methods. Any field values set in a <code>Calendar</code> will not be
99 * interpreted until it needs to calculate its time value (milliseconds from
100 * the Epoch) or values of the calendar fields. Calling the
101 * <code>get</code>, <code>getTimeInMillis</code>, <code>getTime</code>,
102 * <code>add</code> and <code>roll</code> involves such calculation.
103 *
104 * <h4>Leniency</h4>
105 *
106 * <p><code>Calendar</code> has two modes for interpreting the calendar
107 * fields, <em>lenient</em> and <em>non-lenient</em>.  When a
108 * <code>Calendar</code> is in lenient mode, it accepts a wider range of
109 * calendar field values than it produces.  When a <code>Calendar</code>
110 * recomputes calendar field values for return by <code>get()</code>, all of
111 * the calendar fields are normalized. For example, a lenient
112 * <code>GregorianCalendar</code> interprets <code>MONTH == JANUARY</code>,
113 * <code>DAY_OF_MONTH == 32</code> as February 1.
114
115 * <p>When a <code>Calendar</code> is in non-lenient mode, it throws an
116 * exception if there is any inconsistency in its calendar fields. For
117 * example, a <code>GregorianCalendar</code> always produces
118 * <code>DAY_OF_MONTH</code> values between 1 and the length of the month. A
119 * non-lenient <code>GregorianCalendar</code> throws an exception upon
120 * calculating its time or calendar field values if any out-of-range field
121 * value has been set.
122 *
123 * <h4><a name="first_week">First Week</a></h4>
124 *
125 * <code>Calendar</code> defines a locale-specific seven day week using two
126 * parameters: the first day of the week and the minimal days in first week
127 * (from 1 to 7).  These numbers are taken from the locale resource data when a
128 * <code>Calendar</code> is constructed.  They may also be specified explicitly
129 * through the methods for setting their values.
130 *
131 * <p>When setting or getting the <code>WEEK_OF_MONTH</code> or
132 * <code>WEEK_OF_YEAR</code> fields, <code>Calendar</code> must determine the
133 * first week of the month or year as a reference point.  The first week of a
134 * month or year is defined as the earliest seven day period beginning on
135 * <code>getFirstDayOfWeek()</code> and containing at least
136 * <code>getMinimalDaysInFirstWeek()</code> days of that month or year.  Weeks
137 * numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow
138 * it.  Note that the normalized numbering returned by <code>get()</code> may be
139 * different.  For example, a specific <code>Calendar</code> subclass may
140 * designate the week before week 1 of a year as week <code><i>n</i></code> of
141 * the previous year.
142 *
143 * <h4>Calendar Fields Resolution</h4>
144 *
145 * When computing a date and time from the calendar fields, there
146 * may be insufficient information for the computation (such as only
147 * year and month with no day of month), or there may be inconsistent
148 * information (such as Tuesday, July 15, 1996 (Gregorian) -- July 15,
149 * 1996 is actually a Monday). <code>Calendar</code> will resolve
150 * calendar field values to determine the date and time in the
151 * following way.
152 *
153 * <p>If there is any conflict in calendar field values,
154 * <code>Calendar</code> gives priorities to calendar fields that have been set
155 * more recently. The following are the default combinations of the
156 * calendar fields. The most recent combination, as determined by the
157 * most recently set single field, will be used.
158 *
159 * <p><a name="date_resolution">For the date fields</a>:
160 * <blockquote>
161 * <pre>
162 * YEAR + MONTH + DAY_OF_MONTH
163 * YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
164 * YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
165 * YEAR + DAY_OF_YEAR
166 * YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
167 * </pre></blockquote>
168 *
169 * <a name="time_resolution">For the time of day fields</a>:
170 * <blockquote>
171 * <pre>
172 * HOUR_OF_DAY
173 * AM_PM + HOUR
174 * </pre></blockquote>
175 *
176 * <p>If there are any calendar fields whose values haven't been set in the selected
177 * field combination, <code>Calendar</code> uses their default values. The default
178 * value of each field may vary by concrete calendar systems. For example, in
179 * <code>GregorianCalendar</code>, the default of a field is the same as that
180 * of the start of the Epoch: i.e., <code>YEAR = 1970</code>, <code>MONTH =
181 * JANUARY</code>, <code>DAY_OF_MONTH = 1</code>, etc.
182 *
183 * <p>
184 * <strong>Note:</strong> There are certain possible ambiguities in
185 * interpretation of certain singular times, which are resolved in the
186 * following ways:
187 * <ol>
188 *     <li> 23:59 is the last minute of the day and 00:00 is the first
189 *          minute of the next day. Thus, 23:59 on Dec 31, 1999 &lt; 00:00 on
190 *          Jan 1, 2000 &lt; 00:01 on Jan 1, 2000.
191 *
192 *     <li> Although historically not precise, midnight also belongs to "am",
193 *          and noon belongs to "pm", so on the same day,
194 *          12:00 am (midnight) &lt; 12:01 am, and 12:00 pm (noon) &lt; 12:01 pm
195 * </ol>
196 *
197 * <p>
198 * The date or time format strings are not part of the definition of a
199 * calendar, as those must be modifiable or overridable by the user at
200 * runtime. Use {@link DateFormat}
201 * to format dates.
202 *
203 * <h4>Field Manipulation</h4>
204 *
205 * The calendar fields can be changed using three methods:
206 * <code>set()</code>, <code>add()</code>, and <code>roll()</code>.</p>
207 *
208 * <p><strong><code>set(f, value)</code></strong> changes calendar field
209 * <code>f</code> to <code>value</code>.  In addition, it sets an
210 * internal member variable to indicate that calendar field <code>f</code> has
211 * been changed. Although calendar field <code>f</code> is changed immediately,
212 * the calendar's time value in milliseconds is not recomputed until the next call to
213 * <code>get()</code>, <code>getTime()</code>, <code>getTimeInMillis()</code>,
214 * <code>add()</code>, or <code>roll()</code> is made. Thus, multiple calls to
215 * <code>set()</code> do not trigger multiple, unnecessary
216 * computations. As a result of changing a calendar field using
217 * <code>set()</code>, other calendar fields may also change, depending on the
218 * calendar field, the calendar field value, and the calendar system. In addition,
219 * <code>get(f)</code> will not necessarily return <code>value</code> set by
220 * the call to the <code>set</code> method
221 * after the calendar fields have been recomputed. The specifics are determined by
222 * the concrete calendar class.</p>
223 *
224 * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
225 * originally set to August 31, 1999. Calling <code>set(Calendar.MONTH,
226 * Calendar.SEPTEMBER)</code> sets the date to September 31,
227 * 1999. This is a temporary internal representation that resolves to
228 * October 1, 1999 if <code>getTime()</code>is then called. However, a
229 * call to <code>set(Calendar.DAY_OF_MONTH, 30)</code> before the call to
230 * <code>getTime()</code> sets the date to September 30, 1999, since
231 * no recomputation occurs after <code>set()</code> itself.</p>
232 *
233 * <p><strong><code>add(f, delta)</code></strong> adds <code>delta</code>
234 * to field <code>f</code>.  This is equivalent to calling <code>set(f,
235 * get(f) + delta)</code> with two adjustments:</p>
236 *
237 * <blockquote>
238 *   <p><strong>Add rule 1</strong>. The value of field <code>f</code>
239 *   after the call minus the value of field <code>f</code> before the
240 *   call is <code>delta</code>, modulo any overflow that has occurred in
241 *   field <code>f</code>. Overflow occurs when a field value exceeds its
242 *   range and, as a result, the next larger field is incremented or
243 *   decremented and the field value is adjusted back into its range.</p>
244 *
245 *   <p><strong>Add rule 2</strong>. If a smaller field is expected to be
246 *   invariant, but it is impossible for it to be equal to its
247 *   prior value because of changes in its minimum or maximum after field
248 *   <code>f</code> is changed or other constraints, such as time zone
249 *   offset changes, then its value is adjusted to be as close
250 *   as possible to its expected value. A smaller field represents a
251 *   smaller unit of time. <code>HOUR</code> is a smaller field than
252 *   <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields
253 *   that are not expected to be invariant. The calendar system
254 *   determines what fields are expected to be invariant.</p>
255 * </blockquote>
256 *
257 * <p>In addition, unlike <code>set()</code>, <code>add()</code> forces
258 * an immediate recomputation of the calendar's milliseconds and all
259 * fields.</p>
260 *
261 * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
262 * originally set to August 31, 1999. Calling <code>add(Calendar.MONTH,
263 * 13)</code> sets the calendar to September 30, 2000. <strong>Add rule
264 * 1</strong> sets the <code>MONTH</code> field to September, since
265 * adding 13 months to August gives September of the next year. Since
266 * <code>DAY_OF_MONTH</code> cannot be 31 in September in a
267 * <code>GregorianCalendar</code>, <strong>add rule 2</strong> sets the
268 * <code>DAY_OF_MONTH</code> to 30, the closest possible value. Although
269 * it is a smaller field, <code>DAY_OF_WEEK</code> is not adjusted by
270 * rule 2, since it is expected to change when the month changes in a
271 * <code>GregorianCalendar</code>.</p>
272 *
273 * <p><strong><code>roll(f, delta)</code></strong> adds
274 * <code>delta</code> to field <code>f</code> without changing larger
275 * fields. This is equivalent to calling <code>add(f, delta)</code> with
276 * the following adjustment:</p>
277 *
278 * <blockquote>
279 *   <p><strong>Roll rule</strong>. Larger fields are unchanged after the
280 *   call. A larger field represents a larger unit of
281 *   time. <code>DAY_OF_MONTH</code> is a larger field than
282 *   <code>HOUR</code>.</p>
283 * </blockquote>
284 *
285 * <p><em>Example</em>: See {@link java.util.GregorianCalendar#roll(int, int)}.
286 *
287 * <p><strong>Usage model</strong>. To motivate the behavior of
288 * <code>add()</code> and <code>roll()</code>, consider a user interface
289 * component with increment and decrement buttons for the month, day, and
290 * year, and an underlying <code>GregorianCalendar</code>. If the
291 * interface reads January 31, 1999 and the user presses the month
292 * increment button, what should it read? If the underlying
293 * implementation uses <code>set()</code>, it might read March 3, 1999. A
294 * better result would be February 28, 1999. Furthermore, if the user
295 * presses the month increment button again, it should read March 31,
296 * 1999, not March 28, 1999. By saving the original date and using either
297 * <code>add()</code> or <code>roll()</code>, depending on whether larger
298 * fields should be affected, the user interface can behave as most users
299 * will intuitively expect.</p>
300 *
301 * @see          java.lang.System#currentTimeMillis()
302 * @see          Date
303 * @see          GregorianCalendar
304 * @see          TimeZone
305 * @see          java.text.DateFormat
306 * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
307 * @since JDK1.1
308 */
309public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> {
310
311    // Data flow in Calendar
312    // ---------------------
313
314    // The current time is represented in two ways by Calendar: as UTC
315    // milliseconds from the epoch (1 January 1970 0:00 UTC), and as local
316    // fields such as MONTH, HOUR, AM_PM, etc.  It is possible to compute the
317    // millis from the fields, and vice versa.  The data needed to do this
318    // conversion is encapsulated by a TimeZone object owned by the Calendar.
319    // The data provided by the TimeZone object may also be overridden if the
320    // user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class
321    // keeps track of what information was most recently set by the caller, and
322    // uses that to compute any other information as needed.
323
324    // If the user sets the fields using set(), the data flow is as follows.
325    // This is implemented by the Calendar subclass's computeTime() method.
326    // During this process, certain fields may be ignored.  The disambiguation
327    // algorithm for resolving which fields to pay attention to is described
328    // in the class documentation.
329
330    //   local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
331    //           |
332    //           | Using Calendar-specific algorithm
333    //           V
334    //   local standard millis
335    //           |
336    //           | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET
337    //           V
338    //   UTC millis (in time data member)
339
340    // If the user sets the UTC millis using setTime() or setTimeInMillis(),
341    // the data flow is as follows.  This is implemented by the Calendar
342    // subclass's computeFields() method.
343
344    //   UTC millis (in time data member)
345    //           |
346    //           | Using TimeZone getOffset()
347    //           V
348    //   local standard millis
349    //           |
350    //           | Using Calendar-specific algorithm
351    //           V
352    //   local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
353
354    // In general, a round trip from fields, through local and UTC millis, and
355    // back out to fields is made when necessary.  This is implemented by the
356    // complete() method.  Resolving a partial set of fields into a UTC millis
357    // value allows all remaining fields to be generated from that value.  If
358    // the Calendar is lenient, the fields are also renormalized to standard
359    // ranges when they are regenerated.
360
361    /**
362     * Field number for <code>get</code> and <code>set</code> indicating the
363     * era, e.g., AD or BC in the Julian calendar. This is a calendar-specific
364     * value; see subclass documentation.
365     *
366     * @see GregorianCalendar#AD
367     * @see GregorianCalendar#BC
368     */
369    public final static int ERA = 0;
370
371    /**
372     * Field number for <code>get</code> and <code>set</code> indicating the
373     * year. This is a calendar-specific value; see subclass documentation.
374     */
375    public final static int YEAR = 1;
376
377    /**
378     * Field number for <code>get</code> and <code>set</code> indicating the
379     * month. This is a calendar-specific value. The first month of
380     * the year in the Gregorian and Julian calendars is
381     * <code>JANUARY</code> which is 0; the last depends on the number
382     * of months in a year.
383     *
384     * @see #JANUARY
385     * @see #FEBRUARY
386     * @see #MARCH
387     * @see #APRIL
388     * @see #MAY
389     * @see #JUNE
390     * @see #JULY
391     * @see #AUGUST
392     * @see #SEPTEMBER
393     * @see #OCTOBER
394     * @see #NOVEMBER
395     * @see #DECEMBER
396     * @see #UNDECIMBER
397     */
398    public final static int MONTH = 2;
399
400    /**
401     * Field number for <code>get</code> and <code>set</code> indicating the
402     * week number within the current year.  The first week of the year, as
403     * defined by <code>getFirstDayOfWeek()</code> and
404     * <code>getMinimalDaysInFirstWeek()</code>, has value 1.  Subclasses define
405     * the value of <code>WEEK_OF_YEAR</code> for days before the first week of
406     * the year.
407     *
408     * @see #getFirstDayOfWeek
409     * @see #getMinimalDaysInFirstWeek
410     */
411    public final static int WEEK_OF_YEAR = 3;
412
413    /**
414     * Field number for <code>get</code> and <code>set</code> indicating the
415     * week number within the current month.  The first week of the month, as
416     * defined by <code>getFirstDayOfWeek()</code> and
417     * <code>getMinimalDaysInFirstWeek()</code>, has value 1.  Subclasses define
418     * the value of <code>WEEK_OF_MONTH</code> for days before the first week of
419     * the month.
420     *
421     * @see #getFirstDayOfWeek
422     * @see #getMinimalDaysInFirstWeek
423     */
424    public final static int WEEK_OF_MONTH = 4;
425
426    /**
427     * Field number for <code>get</code> and <code>set</code> indicating the
428     * day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.
429     * The first day of the month has value 1.
430     *
431     * @see #DAY_OF_MONTH
432     */
433    public final static int DATE = 5;
434
435    /**
436     * Field number for <code>get</code> and <code>set</code> indicating the
437     * day of the month. This is a synonym for <code>DATE</code>.
438     * The first day of the month has value 1.
439     *
440     * @see #DATE
441     */
442    public final static int DAY_OF_MONTH = 5;
443
444    /**
445     * Field number for <code>get</code> and <code>set</code> indicating the day
446     * number within the current year.  The first day of the year has value 1.
447     */
448    public final static int DAY_OF_YEAR = 6;
449
450    /**
451     * Field number for <code>get</code> and <code>set</code> indicating the day
452     * of the week.  This field takes values <code>SUNDAY</code>,
453     * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>,
454     * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.
455     *
456     * @see #SUNDAY
457     * @see #MONDAY
458     * @see #TUESDAY
459     * @see #WEDNESDAY
460     * @see #THURSDAY
461     * @see #FRIDAY
462     * @see #SATURDAY
463     */
464    public final static int DAY_OF_WEEK = 7;
465
466    /**
467     * Field number for <code>get</code> and <code>set</code> indicating the
468     * ordinal number of the day of the week within the current month. Together
469     * with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day
470     * within a month.  Unlike <code>WEEK_OF_MONTH</code> and
471     * <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on
472     * <code>getFirstDayOfWeek()</code> or
473     * <code>getMinimalDaysInFirstWeek()</code>.  <code>DAY_OF_MONTH 1</code>
474     * through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH
475     * 1</code>; <code>8</code> through <code>14</code> correspond to
476     * <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on.
477     * <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before
478     * <code>DAY_OF_WEEK_IN_MONTH 1</code>.  Negative values count back from the
479     * end of the month, so the last Sunday of a month is specified as
480     * <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>.  Because
481     * negative values count backward they will usually be aligned differently
482     * within the month than positive values.  For example, if a month has 31
483     * days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap
484     * <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>.
485     *
486     * @see #DAY_OF_WEEK
487     * @see #WEEK_OF_MONTH
488     */
489    public final static int DAY_OF_WEEK_IN_MONTH = 8;
490
491    /**
492     * Field number for <code>get</code> and <code>set</code> indicating
493     * whether the <code>HOUR</code> is before or after noon.
494     * E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>.
495     *
496     * @see #AM
497     * @see #PM
498     * @see #HOUR
499     */
500    public final static int AM_PM = 9;
501
502    /**
503     * Field number for <code>get</code> and <code>set</code> indicating the
504     * hour of the morning or afternoon. <code>HOUR</code> is used for the
505     * 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12.
506     * E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10.
507     *
508     * @see #AM_PM
509     * @see #HOUR_OF_DAY
510     */
511    public final static int HOUR = 10;
512
513    /**
514     * Field number for <code>get</code> and <code>set</code> indicating the
515     * hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock.
516     * E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22.
517     *
518     * @see #HOUR
519     */
520    public final static int HOUR_OF_DAY = 11;
521
522    /**
523     * Field number for <code>get</code> and <code>set</code> indicating the
524     * minute within the hour.
525     * E.g., at 10:04:15.250 PM the <code>MINUTE</code> is 4.
526     */
527    public final static int MINUTE = 12;
528
529    /**
530     * Field number for <code>get</code> and <code>set</code> indicating the
531     * second within the minute.
532     * E.g., at 10:04:15.250 PM the <code>SECOND</code> is 15.
533     */
534    public final static int SECOND = 13;
535
536    /**
537     * Field number for <code>get</code> and <code>set</code> indicating the
538     * millisecond within the second.
539     * E.g., at 10:04:15.250 PM the <code>MILLISECOND</code> is 250.
540     */
541    public final static int MILLISECOND = 14;
542
543    /**
544     * Field number for <code>get</code> and <code>set</code>
545     * indicating the raw offset from GMT in milliseconds.
546     * <p>
547     * This field reflects the correct GMT offset value of the time
548     * zone of this <code>Calendar</code> if the
549     * <code>TimeZone</code> implementation subclass supports
550     * historical GMT offset changes.
551     */
552    public final static int ZONE_OFFSET = 15;
553
554    /**
555     * Field number for <code>get</code> and <code>set</code> indicating the
556     * daylight saving offset in milliseconds.
557     * <p>
558     * This field reflects the correct daylight saving offset value of
559     * the time zone of this <code>Calendar</code> if the
560     * <code>TimeZone</code> implementation subclass supports
561     * historical Daylight Saving Time schedule changes.
562     */
563    public final static int DST_OFFSET = 16;
564
565    /**
566     * The number of distinct fields recognized by <code>get</code> and <code>set</code>.
567     * Field numbers range from <code>0..FIELD_COUNT-1</code>.
568     */
569    public final static int FIELD_COUNT = 17;
570
571    /**
572     * Value of the {@link #DAY_OF_WEEK} field indicating
573     * Sunday.
574     */
575    public final static int SUNDAY = 1;
576
577    /**
578     * Value of the {@link #DAY_OF_WEEK} field indicating
579     * Monday.
580     */
581    public final static int MONDAY = 2;
582
583    /**
584     * Value of the {@link #DAY_OF_WEEK} field indicating
585     * Tuesday.
586     */
587    public final static int TUESDAY = 3;
588
589    /**
590     * Value of the {@link #DAY_OF_WEEK} field indicating
591     * Wednesday.
592     */
593    public final static int WEDNESDAY = 4;
594
595    /**
596     * Value of the {@link #DAY_OF_WEEK} field indicating
597     * Thursday.
598     */
599    public final static int THURSDAY = 5;
600
601    /**
602     * Value of the {@link #DAY_OF_WEEK} field indicating
603     * Friday.
604     */
605    public final static int FRIDAY = 6;
606
607    /**
608     * Value of the {@link #DAY_OF_WEEK} field indicating
609     * Saturday.
610     */
611    public final static int SATURDAY = 7;
612
613    /**
614     * Value of the {@link #MONTH} field indicating the
615     * first month of the year in the Gregorian and Julian calendars.
616     */
617    public final static int JANUARY = 0;
618
619    /**
620     * Value of the {@link #MONTH} field indicating the
621     * second month of the year in the Gregorian and Julian calendars.
622     */
623    public final static int FEBRUARY = 1;
624
625    /**
626     * Value of the {@link #MONTH} field indicating the
627     * third month of the year in the Gregorian and Julian calendars.
628     */
629    public final static int MARCH = 2;
630
631    /**
632     * Value of the {@link #MONTH} field indicating the
633     * fourth month of the year in the Gregorian and Julian calendars.
634     */
635    public final static int APRIL = 3;
636
637    /**
638     * Value of the {@link #MONTH} field indicating the
639     * fifth month of the year in the Gregorian and Julian calendars.
640     */
641    public final static int MAY = 4;
642
643    /**
644     * Value of the {@link #MONTH} field indicating the
645     * sixth month of the year in the Gregorian and Julian calendars.
646     */
647    public final static int JUNE = 5;
648
649    /**
650     * Value of the {@link #MONTH} field indicating the
651     * seventh month of the year in the Gregorian and Julian calendars.
652     */
653    public final static int JULY = 6;
654
655    /**
656     * Value of the {@link #MONTH} field indicating the
657     * eighth month of the year in the Gregorian and Julian calendars.
658     */
659    public final static int AUGUST = 7;
660
661    /**
662     * Value of the {@link #MONTH} field indicating the
663     * ninth month of the year in the Gregorian and Julian calendars.
664     */
665    public final static int SEPTEMBER = 8;
666
667    /**
668     * Value of the {@link #MONTH} field indicating the
669     * tenth month of the year in the Gregorian and Julian calendars.
670     */
671    public final static int OCTOBER = 9;
672
673    /**
674     * Value of the {@link #MONTH} field indicating the
675     * eleventh month of the year in the Gregorian and Julian calendars.
676     */
677    public final static int NOVEMBER = 10;
678
679    /**
680     * Value of the {@link #MONTH} field indicating the
681     * twelfth month of the year in the Gregorian and Julian calendars.
682     */
683    public final static int DECEMBER = 11;
684
685    /**
686     * Value of the {@link #MONTH} field indicating the
687     * thirteenth month of the year. Although <code>GregorianCalendar</code>
688     * does not use this value, lunar calendars do.
689     */
690    public final static int UNDECIMBER = 12;
691
692    /**
693     * Value of the {@link #AM_PM} field indicating the
694     * period of the day from midnight to just before noon.
695     */
696    public final static int AM = 0;
697
698    /**
699     * Value of the {@link #AM_PM} field indicating the
700     * period of the day from noon to just before midnight.
701     */
702    public final static int PM = 1;
703
704    /**
705     * A style specifier for {@link #getDisplayNames(int, int, Locale)
706     * getDisplayNames} indicating names in all styles, such as
707     * "January" and "Jan".
708     *
709     * @see #SHORT
710     * @see #LONG
711     * @since 1.6
712     */
713    public static final int ALL_STYLES = 0;
714
715    /**
716     * A style specifier for {@link #getDisplayName(int, int, Locale)
717     * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
718     * getDisplayNames} indicating a short name, such as "Jan".
719     *
720     * @see #LONG
721     * @since 1.6
722     */
723    public static final int SHORT = 1;
724
725    /**
726     * A style specifier for {@link #getDisplayName(int, int, Locale)
727     * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
728     * getDisplayNames} indicating a long name, such as "January".
729     *
730     * @see #SHORT
731     * @since 1.6
732     */
733    public static final int LONG = 2;
734
735    // Internal notes:
736    // Calendar contains two kinds of time representations: current "time" in
737    // milliseconds, and a set of calendar "fields" representing the current time.
738    // The two representations are usually in sync, but can get out of sync
739    // as follows.
740    // 1. Initially, no fields are set, and the time is invalid.
741    // 2. If the time is set, all fields are computed and in sync.
742    // 3. If a single field is set, the time is invalid.
743    // Recomputation of the time and fields happens when the object needs
744    // to return a result to the user, or use a result for a computation.
745
746    /**
747     * The calendar field values for the currently set time for this calendar.
748     * This is an array of <code>FIELD_COUNT</code> integers, with index values
749     * <code>ERA</code> through <code>DST_OFFSET</code>.
750     * @serial
751     */
752    protected int           fields[];
753
754    /**
755     * The flags which tell if a specified calendar field for the calendar is set.
756     * A new object has no fields set.  After the first call to a method
757     * which generates the fields, they all remain set after that.
758     * This is an array of <code>FIELD_COUNT</code> booleans, with index values
759     * <code>ERA</code> through <code>DST_OFFSET</code>.
760     * @serial
761     */
762    protected boolean       isSet[];
763
764    /**
765     * Pseudo-time-stamps which specify when each field was set. There
766     * are two special values, UNSET and COMPUTED. Values from
767     * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values.
768     */
769    transient private int   stamp[];
770
771    /**
772     * The currently set time for this calendar, expressed in milliseconds after
773     * January 1, 1970, 0:00:00 GMT.
774     * @see #isTimeSet
775     * @serial
776     */
777    protected long          time;
778
779    /**
780     * True if then the value of <code>time</code> is valid.
781     * The time is made invalid by a change to an item of <code>field[]</code>.
782     * @see #time
783     * @serial
784     */
785    protected boolean       isTimeSet;
786
787    /**
788     * True if <code>fields[]</code> are in sync with the currently set time.
789     * If false, then the next attempt to get the value of a field will
790     * force a recomputation of all fields from the current value of
791     * <code>time</code>.
792     * @serial
793     */
794    protected boolean       areFieldsSet;
795
796    /**
797     * True if all fields have been set.
798     * @serial
799     */
800    transient boolean       areAllFieldsSet;
801
802    /**
803     * <code>True</code> if this calendar allows out-of-range field values during computation
804     * of <code>time</code> from <code>fields[]</code>.
805     * @see #setLenient
806     * @see #isLenient
807     * @serial
808     */
809    private boolean         lenient = true;
810
811    /**
812     * The <code>TimeZone</code> used by this calendar. <code>Calendar</code>
813     * uses the time zone data to translate between locale and GMT time.
814     * @serial
815     */
816    private TimeZone        zone;
817
818    /**
819     * <code>True</code> if zone references to a shared TimeZone object.
820     */
821    transient private boolean sharedZone = false;
822
823    /**
824     * The first day of the week, with possible values <code>SUNDAY</code>,
825     * <code>MONDAY</code>, etc.  This is a locale-dependent value.
826     * @serial
827     */
828    private int             firstDayOfWeek;
829
830    /**
831     * The number of days required for the first week in a month or year,
832     * with possible values from 1 to 7.  This is a locale-dependent value.
833     * @serial
834     */
835    private int             minimalDaysInFirstWeek;
836
837    /**
838     * Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek
839     * of a Locale.
840     */
841    private static final ConcurrentMap<Locale, int[]> cachedLocaleData
842        = new ConcurrentHashMap<Locale, int[]>(3);
843
844    // Special values of stamp[]
845    /**
846     * The corresponding fields[] has no value.
847     */
848    private static final int        UNSET = 0;
849
850    /**
851     * The value of the corresponding fields[] has been calculated internally.
852     */
853    private static final int        COMPUTED = 1;
854
855    /**
856     * The value of the corresponding fields[] has been set externally. Stamp
857     * values which are greater than 1 represents the (pseudo) time when the
858     * corresponding fields[] value was set.
859     */
860    private static final int        MINIMUM_USER_STAMP = 2;
861
862    /**
863     * The mask value that represents all of the fields.
864     */
865    static final int ALL_FIELDS = (1 << FIELD_COUNT) - 1;
866
867    /**
868     * The next available value for <code>stamp[]</code>, an internal array.
869     * This actually should not be written out to the stream, and will probably
870     * be removed from the stream in the near future.  In the meantime,
871     * a value of <code>MINIMUM_USER_STAMP</code> should be used.
872     * @serial
873     */
874    private int             nextStamp = MINIMUM_USER_STAMP;
875
876    // the internal serial version which says which version was written
877    // - 0 (default) for version up to JDK 1.1.5
878    // - 1 for version from JDK 1.1.6, which writes a correct 'time' value
879    //     as well as compatible values for other fields.  This is a
880    //     transitional format.
881    // - 2 (not implemented yet) a future version, in which fields[],
882    //     areFieldsSet, and isTimeSet become transient, and isSet[] is
883    //     removed. In JDK 1.1.6 we write a format compatible with version 2.
884    static final int        currentSerialVersion = 1;
885
886    /**
887     * The version of the serialized data on the stream.  Possible values:
888     * <dl>
889     * <dt><b>0</b> or not present on stream</dt>
890     * <dd>
891     * JDK 1.1.5 or earlier.
892     * </dd>
893     * <dt><b>1</b></dt>
894     * <dd>
895     * JDK 1.1.6 or later.  Writes a correct 'time' value
896     * as well as compatible values for other fields.  This is a
897     * transitional format.
898     * </dd>
899     * </dl>
900     * When streaming out this class, the most recent format
901     * and the highest allowable <code>serialVersionOnStream</code>
902     * is written.
903     * @serial
904     * @since JDK1.1.6
905     */
906    private int             serialVersionOnStream = currentSerialVersion;
907
908    // Proclaim serialization compatibility with JDK 1.1
909    static final long       serialVersionUID = -1807547505821590642L;
910
911    // Mask values for calendar fields
912    final static int ERA_MASK           = (1 << ERA);
913    final static int YEAR_MASK          = (1 << YEAR);
914    final static int MONTH_MASK         = (1 << MONTH);
915    final static int WEEK_OF_YEAR_MASK  = (1 << WEEK_OF_YEAR);
916    final static int WEEK_OF_MONTH_MASK = (1 << WEEK_OF_MONTH);
917    final static int DAY_OF_MONTH_MASK  = (1 << DAY_OF_MONTH);
918    final static int DATE_MASK          = DAY_OF_MONTH_MASK;
919    final static int DAY_OF_YEAR_MASK   = (1 << DAY_OF_YEAR);
920    final static int DAY_OF_WEEK_MASK   = (1 << DAY_OF_WEEK);
921    final static int DAY_OF_WEEK_IN_MONTH_MASK  = (1 << DAY_OF_WEEK_IN_MONTH);
922    final static int AM_PM_MASK         = (1 << AM_PM);
923    final static int HOUR_MASK          = (1 << HOUR);
924    final static int HOUR_OF_DAY_MASK   = (1 << HOUR_OF_DAY);
925    final static int MINUTE_MASK        = (1 << MINUTE);
926    final static int SECOND_MASK        = (1 << SECOND);
927    final static int MILLISECOND_MASK   = (1 << MILLISECOND);
928    final static int ZONE_OFFSET_MASK   = (1 << ZONE_OFFSET);
929    final static int DST_OFFSET_MASK    = (1 << DST_OFFSET);
930
931    /**
932     * Constructs a Calendar with the default time zone
933     * and locale.
934     * @see     TimeZone#getDefault
935     */
936    protected Calendar()
937    {
938        this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
939        sharedZone = true;
940    }
941
942    /**
943     * Constructs a calendar with the specified time zone and locale.
944     *
945     * @param zone the time zone to use
946     * @param aLocale the locale for the week data
947     */
948    protected Calendar(TimeZone zone, Locale aLocale)
949    {
950        // http://b/16938922.
951        //
952        // TODO: This is for backwards compatibility only. Seems like a better idea to throw
953        // here. We should add a targetSdkVersion based check and throw for this case.
954        if (aLocale == null) {
955            aLocale = Locale.getDefault();
956        }
957        fields = new int[FIELD_COUNT];
958        isSet = new boolean[FIELD_COUNT];
959        stamp = new int[FIELD_COUNT];
960
961        this.zone = zone;
962        setWeekCountData(aLocale);
963    }
964
965    /**
966     * Gets a calendar using the default time zone and locale. The
967     * <code>Calendar</code> returned is based on the current time
968     * in the default time zone with the default locale.
969     *
970     * @return a Calendar.
971     */
972    public static Calendar getInstance()
973    {
974        Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
975        cal.sharedZone = true;
976        return cal;
977    }
978
979    /**
980     * Gets a calendar using the specified time zone and default locale.
981     * The <code>Calendar</code> returned is based on the current time
982     * in the given time zone with the default locale.
983     *
984     * @param zone the time zone to use
985     * @return a Calendar.
986     */
987    public static Calendar getInstance(TimeZone zone)
988    {
989        return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT));
990    }
991
992    /**
993     * Gets a calendar using the default time zone and specified locale.
994     * The <code>Calendar</code> returned is based on the current time
995     * in the default time zone with the given locale.
996     *
997     * @param aLocale the locale for the week data
998     * @return a Calendar.
999     */
1000    public static Calendar getInstance(Locale aLocale)
1001    {
1002        Calendar cal = createCalendar(TimeZone.getDefaultRef(), aLocale);
1003        cal.sharedZone = true;
1004        return cal;
1005    }
1006
1007    /**
1008     * Gets a calendar with the specified time zone and locale.
1009     * The <code>Calendar</code> returned is based on the current time
1010     * in the given time zone with the given locale.
1011     *
1012     * @param zone the time zone to use
1013     * @param aLocale the locale for the week data
1014     * @return a Calendar.
1015     */
1016    public static Calendar getInstance(TimeZone zone,
1017                                       Locale aLocale)
1018    {
1019        return createCalendar(zone, aLocale);
1020    }
1021
1022    private static Calendar createCalendar(TimeZone zone,
1023                                           Locale aLocale)
1024    {
1025        return new GregorianCalendar(zone, aLocale);
1026    }
1027
1028    /**
1029     * Returns an array of all locales for which the <code>getInstance</code>
1030     * methods of this class can return localized instances.
1031     * The array returned must contain at least a <code>Locale</code>
1032     * instance equal to {@link java.util.Locale#US Locale.US}.
1033     *
1034     * @return An array of locales for which localized
1035     *         <code>Calendar</code> instances are available.
1036     */
1037    public static synchronized Locale[] getAvailableLocales()
1038    {
1039        return DateFormat.getAvailableLocales();
1040    }
1041
1042    /**
1043     * Converts the current calendar field values in {@link #fields fields[]}
1044     * to the millisecond time value
1045     * {@link #time}.
1046     *
1047     * @see #complete()
1048     * @see #computeFields()
1049     */
1050    protected abstract void computeTime();
1051
1052    /**
1053     * Converts the current millisecond time value {@link #time}
1054     * to calendar field values in {@link #fields fields[]}.
1055     * This allows you to sync up the calendar field values with
1056     * a new time that is set for the calendar.  The time is <em>not</em>
1057     * recomputed first; to recompute the time, then the fields, call the
1058     * {@link #complete()} method.
1059     *
1060     * @see #computeTime()
1061     */
1062    protected abstract void computeFields();
1063
1064    /**
1065     * Returns a <code>Date</code> object representing this
1066     * <code>Calendar</code>'s time value (millisecond offset from the <a
1067     * href="#Epoch">Epoch</a>").
1068     *
1069     * @return a <code>Date</code> representing the time value.
1070     * @see #setTime(Date)
1071     * @see #getTimeInMillis()
1072     */
1073    public final Date getTime() {
1074        return new Date(getTimeInMillis());
1075    }
1076
1077    /**
1078     * Sets this Calendar's time with the given <code>Date</code>.
1079     * <p>
1080     * Note: Calling <code>setTime()</code> with
1081     * <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code>
1082     * may yield incorrect field values from <code>get()</code>.
1083     *
1084     * @param date the given Date.
1085     * @see #getTime()
1086     * @see #setTimeInMillis(long)
1087     */
1088    public final void setTime(Date date) {
1089        setTimeInMillis(date.getTime());
1090    }
1091
1092    /**
1093     * Returns this Calendar's time value in milliseconds.
1094     *
1095     * @return the current time as UTC milliseconds from the epoch.
1096     * @see #getTime()
1097     * @see #setTimeInMillis(long)
1098     */
1099    public long getTimeInMillis() {
1100        if (!isTimeSet) {
1101            updateTime();
1102        }
1103        return time;
1104    }
1105
1106    /**
1107     * Sets this Calendar's current time from the given long value.
1108     *
1109     * @param millis the new time in UTC milliseconds from the epoch.
1110     * @see #setTime(Date)
1111     * @see #getTimeInMillis()
1112     */
1113    public void setTimeInMillis(long millis) {
1114        // If we don't need to recalculate the calendar field values,
1115        // do nothing.
1116        if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet) {
1117            return;
1118        }
1119        time = millis;
1120        isTimeSet = true;
1121        areFieldsSet = false;
1122        computeFields();
1123        areAllFieldsSet = areFieldsSet = true;
1124    }
1125
1126    /**
1127     * Returns the value of the given calendar field. In lenient mode,
1128     * all calendar fields are normalized. In non-lenient mode, all
1129     * calendar fields are validated and this method throws an
1130     * exception if any calendar fields have out-of-range values. The
1131     * normalization and validation are handled by the
1132     * {@link #complete()} method, which process is calendar
1133     * system dependent.
1134     *
1135     * @param field the given calendar field.
1136     * @return the value for the given calendar field.
1137     * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
1138     *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1139     * @see #set(int,int)
1140     * @see #complete()
1141     */
1142    public int get(int field)
1143    {
1144        complete();
1145        return internalGet(field);
1146    }
1147
1148    /**
1149     * Returns the value of the given calendar field. This method does
1150     * not involve normalization or validation of the field value.
1151     *
1152     * @param field the given calendar field.
1153     * @return the value for the given calendar field.
1154     * @see #get(int)
1155     */
1156    protected final int internalGet(int field)
1157    {
1158        return fields[field];
1159    }
1160
1161    /**
1162     * Sets the value of the given calendar field. This method does
1163     * not affect any setting state of the field in this
1164     * <code>Calendar</code> instance.
1165     *
1166     * @throws IndexOutOfBoundsException if the specified field is out of range
1167     *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1168     * @see #areFieldsSet
1169     * @see #isTimeSet
1170     * @see #areAllFieldsSet
1171     * @see #set(int,int)
1172     */
1173    final void internalSet(int field, int value)
1174    {
1175        fields[field] = value;
1176    }
1177
1178    /**
1179     * Sets the given calendar field to the given value. The value is not
1180     * interpreted by this method regardless of the leniency mode.
1181     *
1182     * @param field the given calendar field.
1183     * @param value the value to be set for the given calendar field.
1184     * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
1185     *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1186     * in non-lenient mode.
1187     * @see #set(int,int,int)
1188     * @see #set(int,int,int,int,int)
1189     * @see #set(int,int,int,int,int,int)
1190     * @see #get(int)
1191     */
1192    public void set(int field, int value)
1193    {
1194        // If the fields are partially normalized, calculate all the
1195        // fields before changing any fields.
1196        if (areFieldsSet && !areAllFieldsSet) {
1197            computeFields();
1198        }
1199        internalSet(field, value);
1200        isTimeSet = false;
1201        areFieldsSet = false;
1202        isSet[field] = true;
1203        stamp[field] = nextStamp++;
1204        if (nextStamp == Integer.MAX_VALUE) {
1205            adjustStamp();
1206        }
1207    }
1208
1209    /**
1210     * Sets the values for the calendar fields <code>YEAR</code>,
1211     * <code>MONTH</code>, and <code>DAY_OF_MONTH</code>.
1212     * Previous values of other calendar fields are retained.  If this is not desired,
1213     * call {@link #clear()} first.
1214     *
1215     * @param year the value used to set the <code>YEAR</code> calendar field.
1216     * @param month the value used to set the <code>MONTH</code> calendar field.
1217     * Month value is 0-based. e.g., 0 for January.
1218     * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1219     * @see #set(int,int)
1220     * @see #set(int,int,int,int,int)
1221     * @see #set(int,int,int,int,int,int)
1222     */
1223    public final void set(int year, int month, int date)
1224    {
1225        set(YEAR, year);
1226        set(MONTH, month);
1227        set(DATE, date);
1228    }
1229
1230    /**
1231     * Sets the values for the calendar fields <code>YEAR</code>,
1232     * <code>MONTH</code>, <code>DAY_OF_MONTH</code>,
1233     * <code>HOUR_OF_DAY</code>, and <code>MINUTE</code>.
1234     * Previous values of other fields are retained.  If this is not desired,
1235     * call {@link #clear()} first.
1236     *
1237     * @param year the value used to set the <code>YEAR</code> calendar field.
1238     * @param month the value used to set the <code>MONTH</code> calendar field.
1239     * Month value is 0-based. e.g., 0 for January.
1240     * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1241     * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
1242     * @param minute the value used to set the <code>MINUTE</code> calendar field.
1243     * @see #set(int,int)
1244     * @see #set(int,int,int)
1245     * @see #set(int,int,int,int,int,int)
1246     */
1247    public final void set(int year, int month, int date, int hourOfDay, int minute)
1248    {
1249        set(YEAR, year);
1250        set(MONTH, month);
1251        set(DATE, date);
1252        set(HOUR_OF_DAY, hourOfDay);
1253        set(MINUTE, minute);
1254    }
1255
1256    /**
1257     * Sets the values for the fields <code>YEAR</code>, <code>MONTH</code>,
1258     * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, <code>MINUTE</code>, and
1259     * <code>SECOND</code>.
1260     * Previous values of other fields are retained.  If this is not desired,
1261     * call {@link #clear()} first.
1262     *
1263     * @param year the value used to set the <code>YEAR</code> calendar field.
1264     * @param month the value used to set the <code>MONTH</code> calendar field.
1265     * Month value is 0-based. e.g., 0 for January.
1266     * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1267     * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
1268     * @param minute the value used to set the <code>MINUTE</code> calendar field.
1269     * @param second the value used to set the <code>SECOND</code> calendar field.
1270     * @see #set(int,int)
1271     * @see #set(int,int,int)
1272     * @see #set(int,int,int,int,int)
1273     */
1274    public final void set(int year, int month, int date, int hourOfDay, int minute,
1275                          int second)
1276    {
1277        set(YEAR, year);
1278        set(MONTH, month);
1279        set(DATE, date);
1280        set(HOUR_OF_DAY, hourOfDay);
1281        set(MINUTE, minute);
1282        set(SECOND, second);
1283    }
1284
1285    /**
1286     * Sets all the calendar field values and the time value
1287     * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
1288     * this <code>Calendar</code> undefined. This means that {@link
1289     * #isSet(int) isSet()} will return <code>false</code> for all the
1290     * calendar fields, and the date and time calculations will treat
1291     * the fields as if they had never been set. A
1292     * <code>Calendar</code> implementation class may use its specific
1293     * default field values for date/time calculations. For example,
1294     * <code>GregorianCalendar</code> uses 1970 if the
1295     * <code>YEAR</code> field value is undefined.
1296     *
1297     * @see #clear(int)
1298     */
1299    public final void clear()
1300    {
1301        for (int i = 0; i < fields.length; ) {
1302            stamp[i] = fields[i] = 0; // UNSET == 0
1303            isSet[i++] = false;
1304        }
1305        areAllFieldsSet = areFieldsSet = false;
1306        isTimeSet = false;
1307    }
1308
1309    /**
1310     * Sets the given calendar field value and the time value
1311     * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
1312     * this <code>Calendar</code> undefined. This means that {@link
1313     * #isSet(int) isSet(field)} will return <code>false</code>, and
1314     * the date and time calculations will treat the field as if it
1315     * had never been set. A <code>Calendar</code> implementation
1316     * class may use the field's specific default value for date and
1317     * time calculations.
1318     *
1319     * <p>The {@link #HOUR_OF_DAY}, {@link #HOUR} and {@link #AM_PM}
1320     * fields are handled independently and the <a
1321     * href="#time_resolution">the resolution rule for the time of
1322     * day</a> is applied. Clearing one of the fields doesn't reset
1323     * the hour of day value of this <code>Calendar</code>. Use {@link
1324     * #set(int,int) set(Calendar.HOUR_OF_DAY, 0)} to reset the hour
1325     * value.
1326     *
1327     * @param field the calendar field to be cleared.
1328     * @see #clear()
1329     */
1330    public final void clear(int field)
1331    {
1332        fields[field] = 0;
1333        stamp[field] = UNSET;
1334        isSet[field] = false;
1335
1336        areAllFieldsSet = areFieldsSet = false;
1337        isTimeSet = false;
1338    }
1339
1340    /**
1341     * Determines if the given calendar field has a value set,
1342     * including cases that the value has been set by internal fields
1343     * calculations triggered by a <code>get</code> method call.
1344     *
1345     * @return <code>true</code> if the given calendar field has a value set;
1346     * <code>false</code> otherwise.
1347     */
1348    public final boolean isSet(int field)
1349    {
1350        return stamp[field] != UNSET;
1351    }
1352
1353    /**
1354     * Returns the string representation of the calendar
1355     * <code>field</code> value in the given <code>style</code> and
1356     * <code>locale</code>.  If no string representation is
1357     * applicable, <code>null</code> is returned. This method calls
1358     * {@link Calendar#get(int) get(field)} to get the calendar
1359     * <code>field</code> value if the string representation is
1360     * applicable to the given calendar <code>field</code>.
1361     *
1362     * <p>For example, if this <code>Calendar</code> is a
1363     * <code>GregorianCalendar</code> and its date is 2005-01-01, then
1364     * the string representation of the {@link #MONTH} field would be
1365     * "January" in the long style in an English locale or "Jan" in
1366     * the short style. However, no string representation would be
1367     * available for the {@link #DAY_OF_MONTH} field, and this method
1368     * would return <code>null</code>.
1369     *
1370     * <p>The default implementation supports the calendar fields for
1371     * which a {@link DateFormatSymbols} has names in the given
1372     * <code>locale</code>.
1373     *
1374     * @param field
1375     *        the calendar field for which the string representation
1376     *        is returned
1377     * @param style
1378     *        the style applied to the string representation; one of
1379     *        {@link #SHORT} or {@link #LONG}.
1380     * @param locale
1381     *        the locale for the string representation
1382     * @return the string representation of the given
1383     *        <code>field</code> in the given <code>style</code>, or
1384     *        <code>null</code> if no string representation is
1385     *        applicable.
1386     * @exception IllegalArgumentException
1387     *        if <code>field</code> or <code>style</code> is invalid,
1388     *        or if this <code>Calendar</code> is non-lenient and any
1389     *        of the calendar fields have invalid values
1390     * @exception NullPointerException
1391     *        if <code>locale</code> is null
1392     * @since 1.6
1393     */
1394    public String getDisplayName(int field, int style, Locale locale) {
1395        if (!checkDisplayNameParams(field, style, ALL_STYLES, LONG, locale,
1396                                    ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
1397            return null;
1398        }
1399
1400        DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
1401        String[] strings = getFieldStrings(field, style, symbols);
1402        if (strings != null) {
1403            int fieldValue = get(field);
1404            if (fieldValue < strings.length) {
1405                return strings[fieldValue];
1406            }
1407        }
1408        return null;
1409    }
1410
1411    /**
1412     * Returns a <code>Map</code> containing all names of the calendar
1413     * <code>field</code> in the given <code>style</code> and
1414     * <code>locale</code> and their corresponding field values. For
1415     * example, if this <code>Calendar</code> is a {@link
1416     * GregorianCalendar}, the returned map would contain "Jan" to
1417     * {@link #JANUARY}, "Feb" to {@link #FEBRUARY}, and so on, in the
1418     * {@linkplain #SHORT short} style in an English locale.
1419     *
1420     * <p>The values of other calendar fields may be taken into
1421     * account to determine a set of display names. For example, if
1422     * this <code>Calendar</code> is a lunisolar calendar system and
1423     * the year value given by the {@link #YEAR} field has a leap
1424     * month, this method would return month names containing the leap
1425     * month name, and month names are mapped to their values specific
1426     * for the year.
1427     *
1428     * <p>The default implementation supports display names contained in
1429     * a {@link DateFormatSymbols}. For example, if <code>field</code>
1430     * is {@link #MONTH} and <code>style</code> is {@link
1431     * #ALL_STYLES}, this method returns a <code>Map</code> containing
1432     * all strings returned by {@link DateFormatSymbols#getShortMonths()}
1433     * and {@link DateFormatSymbols#getMonths()}.
1434     *
1435     * @param field
1436     *        the calendar field for which the display names are returned
1437     * @param style
1438     *        the style applied to the display names; one of {@link
1439     *        #SHORT}, {@link #LONG}, or {@link #ALL_STYLES}.
1440     * @param locale
1441     *        the locale for the display names
1442     * @return a <code>Map</code> containing all display names in
1443     *        <code>style</code> and <code>locale</code> and their
1444     *        field values, or <code>null</code> if no display names
1445     *        are defined for <code>field</code>
1446     * @exception IllegalArgumentException
1447     *        if <code>field</code> or <code>style</code> is invalid,
1448     *        or if this <code>Calendar</code> is non-lenient and any
1449     *        of the calendar fields have invalid values
1450     * @exception NullPointerException
1451     *        if <code>locale</code> is null
1452     * @since 1.6
1453     */
1454    public Map<String, Integer> getDisplayNames(int field, int style, Locale locale) {
1455        if (!checkDisplayNameParams(field, style, ALL_STYLES, LONG, locale,
1456                                    ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
1457            return null;
1458        }
1459        complete();
1460
1461        // ALL_STYLES
1462        if (style == ALL_STYLES) {
1463            Map<String,Integer> shortNames = getDisplayNamesImpl(field, SHORT, locale);
1464            if (field == ERA || field == AM_PM) {
1465                return shortNames;
1466            }
1467            Map<String,Integer> longNames = getDisplayNamesImpl(field, LONG, locale);
1468            if (shortNames == null) {
1469                return longNames;
1470            }
1471            if (longNames != null) {
1472                shortNames.putAll(longNames);
1473            }
1474            return shortNames;
1475        }
1476
1477        // SHORT or LONG
1478        return getDisplayNamesImpl(field, style, locale);
1479    }
1480
1481    private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) {
1482        DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
1483        String[] strings = getFieldStrings(field, style, symbols);
1484        if (strings != null) {
1485            Map<String,Integer> names = new HashMap<String,Integer>();
1486            for (int i = 0; i < strings.length; i++) {
1487                if (strings[i].length() == 0) {
1488                    continue;
1489                }
1490                names.put(strings[i], i);
1491            }
1492            return names;
1493        }
1494        return null;
1495    }
1496
1497    boolean checkDisplayNameParams(int field, int style, int minStyle, int maxStyle,
1498                                   Locale locale, int fieldMask) {
1499        if (field < 0 || field >= fields.length ||
1500            style < minStyle || style > maxStyle) {
1501            throw new IllegalArgumentException();
1502        }
1503        if (locale == null) {
1504            throw new NullPointerException();
1505        }
1506        return isFieldSet(fieldMask, field);
1507    }
1508
1509    private String[] getFieldStrings(int field, int style, DateFormatSymbols symbols) {
1510        String[] strings = null;
1511        switch (field) {
1512        case ERA:
1513            strings = symbols.getEras();
1514            break;
1515
1516        case MONTH:
1517            strings = (style == LONG) ? symbols.getMonths() : symbols.getShortMonths();
1518            break;
1519
1520        case DAY_OF_WEEK:
1521            strings = (style == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays();
1522            break;
1523
1524        case AM_PM:
1525            strings = symbols.getAmPmStrings();
1526            break;
1527        }
1528        return strings;
1529    }
1530
1531    /**
1532     * Fills in any unset fields in the calendar fields. First, the {@link
1533     * #computeTime()} method is called if the time value (millisecond offset
1534     * from the <a href="#Epoch">Epoch</a>) has not been calculated from
1535     * calendar field values. Then, the {@link #computeFields()} method is
1536     * called to calculate all calendar field values.
1537     */
1538    protected void complete()
1539    {
1540        if (!isTimeSet)
1541            updateTime();
1542        if (!areFieldsSet || !areAllFieldsSet) {
1543            computeFields(); // fills in unset fields
1544            areAllFieldsSet = areFieldsSet = true;
1545        }
1546    }
1547
1548    /**
1549     * Returns whether the value of the specified calendar field has been set
1550     * externally by calling one of the setter methods rather than by the
1551     * internal time calculation.
1552     *
1553     * @return <code>true</code> if the field has been set externally,
1554     * <code>false</code> otherwise.
1555     * @exception IndexOutOfBoundsException if the specified
1556     *                <code>field</code> is out of range
1557     *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1558     * @see #selectFields()
1559     * @see #setFieldsComputed(int)
1560     */
1561    final boolean isExternallySet(int field) {
1562        return stamp[field] >= MINIMUM_USER_STAMP;
1563    }
1564
1565    /**
1566     * Returns a field mask (bit mask) indicating all calendar fields that
1567     * have the state of externally or internally set.
1568     *
1569     * @return a bit mask indicating set state fields
1570     */
1571    final int getSetStateFields() {
1572        int mask = 0;
1573        for (int i = 0; i < fields.length; i++) {
1574            if (stamp[i] != UNSET) {
1575                mask |= 1 << i;
1576            }
1577        }
1578        return mask;
1579    }
1580
1581    /**
1582     * Sets the state of the specified calendar fields to
1583     * <em>computed</em>. This state means that the specified calendar fields
1584     * have valid values that have been set by internal time calculation
1585     * rather than by calling one of the setter methods.
1586     *
1587     * @param fieldMask the field to be marked as computed.
1588     * @exception IndexOutOfBoundsException if the specified
1589     *                <code>field</code> is out of range
1590     *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1591     * @see #isExternallySet(int)
1592     * @see #selectFields()
1593     */
1594    final void setFieldsComputed(int fieldMask) {
1595        if (fieldMask == ALL_FIELDS) {
1596            for (int i = 0; i < fields.length; i++) {
1597                stamp[i] = COMPUTED;
1598                isSet[i] = true;
1599            }
1600            areFieldsSet = areAllFieldsSet = true;
1601        } else {
1602            for (int i = 0; i < fields.length; i++) {
1603                if ((fieldMask & 1) == 1) {
1604                    stamp[i] = COMPUTED;
1605                    isSet[i] = true;
1606                } else {
1607                    if (areAllFieldsSet && !isSet[i]) {
1608                        areAllFieldsSet = false;
1609                    }
1610                }
1611                fieldMask >>>= 1;
1612            }
1613        }
1614    }
1615
1616    /**
1617     * Sets the state of the calendar fields that are <em>not</em> specified
1618     * by <code>fieldMask</code> to <em>unset</em>. If <code>fieldMask</code>
1619     * specifies all the calendar fields, then the state of this
1620     * <code>Calendar</code> becomes that all the calendar fields are in sync
1621     * with the time value (millisecond offset from the Epoch).
1622     *
1623     * @param fieldMask the field mask indicating which calendar fields are in
1624     * sync with the time value.
1625     * @exception IndexOutOfBoundsException if the specified
1626     *                <code>field</code> is out of range
1627     *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1628     * @see #isExternallySet(int)
1629     * @see #selectFields()
1630     */
1631    final void setFieldsNormalized(int fieldMask) {
1632        if (fieldMask != ALL_FIELDS) {
1633            for (int i = 0; i < fields.length; i++) {
1634                if ((fieldMask & 1) == 0) {
1635                    stamp[i] = fields[i] = 0; // UNSET == 0
1636                    isSet[i] = false;
1637                }
1638                fieldMask >>= 1;
1639            }
1640        }
1641
1642        // Some or all of the fields are in sync with the
1643        // milliseconds, but the stamp values are not normalized yet.
1644        areFieldsSet = true;
1645        areAllFieldsSet = false;
1646    }
1647
1648    /**
1649     * Returns whether the calendar fields are partially in sync with the time
1650     * value or fully in sync but not stamp values are not normalized yet.
1651     */
1652    final boolean isPartiallyNormalized() {
1653        return areFieldsSet && !areAllFieldsSet;
1654    }
1655
1656    /**
1657     * Returns whether the calendar fields are fully in sync with the time
1658     * value.
1659     */
1660    final boolean isFullyNormalized() {
1661        return areFieldsSet && areAllFieldsSet;
1662    }
1663
1664    /**
1665     * Marks this Calendar as not sync'd.
1666     */
1667    final void setUnnormalized() {
1668        areFieldsSet = areAllFieldsSet = false;
1669    }
1670
1671    /**
1672     * Returns whether the specified <code>field</code> is on in the
1673     * <code>fieldMask</code>.
1674     */
1675    static final boolean isFieldSet(int fieldMask, int field) {
1676        return (fieldMask & (1 << field)) != 0;
1677    }
1678
1679    /**
1680     * Returns a field mask indicating which calendar field values
1681     * to be used to calculate the time value. The calendar fields are
1682     * returned as a bit mask, each bit of which corresponds to a field, i.e.,
1683     * the mask value of <code>field</code> is <code>(1 &lt;&lt;
1684     * field)</code>. For example, 0x26 represents the <code>YEAR</code>,
1685     * <code>MONTH</code>, and <code>DAY_OF_MONTH</code> fields (i.e., 0x26 is
1686     * equal to
1687     * <code>(1&lt;&lt;YEAR)|(1&lt;&lt;MONTH)|(1&lt;&lt;DAY_OF_MONTH))</code>.
1688     *
1689     * <p>This method supports the calendar fields resolution as described in
1690     * the class description. If the bit mask for a given field is on and its
1691     * field has not been set (i.e., <code>isSet(field)</code> is
1692     * <code>false</code>), then the default value of the field has to be
1693     * used, which case means that the field has been selected because the
1694     * selected combination involves the field.
1695     *
1696     * @return a bit mask of selected fields
1697     * @see #isExternallySet(int)
1698     * @see #setInternallySetState(int)
1699     */
1700    final int selectFields() {
1701        // This implementation has been taken from the GregorianCalendar class.
1702
1703        // The YEAR field must always be used regardless of its SET
1704        // state because YEAR is a mandatory field to determine the date
1705        // and the default value (EPOCH_YEAR) may change through the
1706        // normalization process.
1707        int fieldMask = YEAR_MASK;
1708
1709        if (stamp[ERA] != UNSET) {
1710            fieldMask |= ERA_MASK;
1711        }
1712        // Find the most recent group of fields specifying the day within
1713        // the year.  These may be any of the following combinations:
1714        //   MONTH + DAY_OF_MONTH
1715        //   MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
1716        //   MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
1717        //   DAY_OF_YEAR
1718        //   WEEK_OF_YEAR + DAY_OF_WEEK
1719        // We look for the most recent of the fields in each group to determine
1720        // the age of the group.  For groups involving a week-related field such
1721        // as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the
1722        // week-related field and the DAY_OF_WEEK must be set for the group as a
1723        // whole to be considered.  (See bug 4153860 - liu 7/24/98.)
1724        int dowStamp = stamp[DAY_OF_WEEK];
1725        int monthStamp = stamp[MONTH];
1726        int domStamp = stamp[DAY_OF_MONTH];
1727        int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp);
1728        int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
1729        int doyStamp = stamp[DAY_OF_YEAR];
1730        int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp);
1731
1732        int bestStamp = domStamp;
1733        if (womStamp > bestStamp) {
1734            bestStamp = womStamp;
1735        }
1736        if (dowimStamp > bestStamp) {
1737            bestStamp = dowimStamp;
1738        }
1739        if (doyStamp > bestStamp) {
1740            bestStamp = doyStamp;
1741        }
1742        if (woyStamp > bestStamp) {
1743            bestStamp = woyStamp;
1744        }
1745
1746        /* No complete combination exists.  Look for WEEK_OF_MONTH,
1747         * DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone.  Treat DAY_OF_WEEK alone
1748         * as DAY_OF_WEEK_IN_MONTH.
1749         */
1750        if (bestStamp == UNSET) {
1751            womStamp = stamp[WEEK_OF_MONTH];
1752            dowimStamp = Math.max(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
1753            woyStamp = stamp[WEEK_OF_YEAR];
1754            bestStamp = Math.max(Math.max(womStamp, dowimStamp), woyStamp);
1755
1756            /* Treat MONTH alone or no fields at all as DAY_OF_MONTH.  This may
1757             * result in bestStamp = domStamp = UNSET if no fields are set,
1758             * which indicates DAY_OF_MONTH.
1759             */
1760            if (bestStamp == UNSET) {
1761                bestStamp = domStamp = monthStamp;
1762            }
1763        }
1764
1765        if (bestStamp == domStamp ||
1766           (bestStamp == womStamp && stamp[WEEK_OF_MONTH] >= stamp[WEEK_OF_YEAR]) ||
1767           (bestStamp == dowimStamp && stamp[DAY_OF_WEEK_IN_MONTH] >= stamp[WEEK_OF_YEAR])) {
1768            fieldMask |= MONTH_MASK;
1769            if (bestStamp == domStamp) {
1770                fieldMask |= DAY_OF_MONTH_MASK;
1771            } else {
1772                assert (bestStamp == womStamp || bestStamp == dowimStamp);
1773                if (dowStamp != UNSET) {
1774                    fieldMask |= DAY_OF_WEEK_MASK;
1775                }
1776                if (womStamp == dowimStamp) {
1777                    // When they are equal, give the priority to
1778                    // WEEK_OF_MONTH for compatibility.
1779                    if (stamp[WEEK_OF_MONTH] >= stamp[DAY_OF_WEEK_IN_MONTH]) {
1780                        fieldMask |= WEEK_OF_MONTH_MASK;
1781                    } else {
1782                        fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
1783                    }
1784                } else {
1785                    if (bestStamp == womStamp) {
1786                        fieldMask |= WEEK_OF_MONTH_MASK;
1787                    } else {
1788                        assert (bestStamp == dowimStamp);
1789                        if (stamp[DAY_OF_WEEK_IN_MONTH] != UNSET) {
1790                            fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
1791                        }
1792                    }
1793                }
1794            }
1795        } else {
1796            assert (bestStamp == doyStamp || bestStamp == woyStamp ||
1797                    bestStamp == UNSET);
1798            if (bestStamp == doyStamp) {
1799                fieldMask |= DAY_OF_YEAR_MASK;
1800            } else {
1801                assert (bestStamp == woyStamp);
1802                if (dowStamp != UNSET) {
1803                    fieldMask |= DAY_OF_WEEK_MASK;
1804                }
1805                fieldMask |= WEEK_OF_YEAR_MASK;
1806            }
1807        }
1808
1809        // Find the best set of fields specifying the time of day.  There
1810        // are only two possibilities here; the HOUR_OF_DAY or the
1811        // AM_PM and the HOUR.
1812        int hourOfDayStamp = stamp[HOUR_OF_DAY];
1813        int hourStamp = aggregateStamp(stamp[HOUR], stamp[AM_PM]);
1814        bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
1815
1816        // if bestStamp is still UNSET, then take HOUR or AM_PM. (See 4846659)
1817        if (bestStamp == UNSET) {
1818            bestStamp = Math.max(stamp[HOUR], stamp[AM_PM]);
1819        }
1820
1821        // Hours
1822        if (bestStamp != UNSET) {
1823            if (bestStamp == hourOfDayStamp) {
1824                fieldMask |= HOUR_OF_DAY_MASK;
1825            } else {
1826                fieldMask |= HOUR_MASK;
1827                if (stamp[AM_PM] != UNSET) {
1828                    fieldMask |= AM_PM_MASK;
1829                }
1830            }
1831        }
1832        if (stamp[MINUTE] != UNSET) {
1833            fieldMask |= MINUTE_MASK;
1834        }
1835        if (stamp[SECOND] != UNSET) {
1836            fieldMask |= SECOND_MASK;
1837        }
1838        if (stamp[MILLISECOND] != UNSET) {
1839            fieldMask |= MILLISECOND_MASK;
1840        }
1841        if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) {
1842                fieldMask |= ZONE_OFFSET_MASK;
1843        }
1844        if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) {
1845            fieldMask |= DST_OFFSET_MASK;
1846        }
1847
1848        return fieldMask;
1849    }
1850
1851    /**
1852     * Returns the pseudo-time-stamp for two fields, given their
1853     * individual pseudo-time-stamps.  If either of the fields
1854     * is unset, then the aggregate is unset.  Otherwise, the
1855     * aggregate is the later of the two stamps.
1856     */
1857    private static final int aggregateStamp(int stamp_a, int stamp_b) {
1858        if (stamp_a == UNSET || stamp_b == UNSET) {
1859            return UNSET;
1860        }
1861        return (stamp_a > stamp_b) ? stamp_a : stamp_b;
1862    }
1863
1864    /**
1865     * Compares this <code>Calendar</code> to the specified
1866     * <code>Object</code>.  The result is <code>true</code> if and only if
1867     * the argument is a <code>Calendar</code> object of the same calendar
1868     * system that represents the same time value (millisecond offset from the
1869     * <a href="#Epoch">Epoch</a>) under the same
1870     * <code>Calendar</code> parameters as this object.
1871     *
1872     * <p>The <code>Calendar</code> parameters are the values represented
1873     * by the <code>isLenient</code>, <code>getFirstDayOfWeek</code>,
1874     * <code>getMinimalDaysInFirstWeek</code> and <code>getTimeZone</code>
1875     * methods. If there is any difference in those parameters
1876     * between the two <code>Calendar</code>s, this method returns
1877     * <code>false</code>.
1878     *
1879     * <p>Use the {@link #compareTo(Calendar) compareTo} method to
1880     * compare only the time values.
1881     *
1882     * @param obj the object to compare with.
1883     * @return <code>true</code> if this object is equal to <code>obj</code>;
1884     * <code>false</code> otherwise.
1885     */
1886    public boolean equals(Object obj) {
1887        if (this == obj)
1888            return true;
1889        try {
1890            Calendar that = (Calendar)obj;
1891            return compareTo(getMillisOf(that)) == 0 &&
1892                lenient == that.lenient &&
1893                firstDayOfWeek == that.firstDayOfWeek &&
1894                minimalDaysInFirstWeek == that.minimalDaysInFirstWeek &&
1895                zone.equals(that.zone);
1896        } catch (Exception e) {
1897            // Note: GregorianCalendar.computeTime throws
1898            // IllegalArgumentException if the ERA value is invalid
1899            // even it's in lenient mode.
1900        }
1901        return false;
1902    }
1903
1904    /**
1905     * Returns a hash code for this calendar.
1906     *
1907     * @return a hash code value for this object.
1908     * @since 1.2
1909     */
1910    public int hashCode() {
1911        // 'otheritems' represents the hash code for the previous versions.
1912        int otheritems = (lenient ? 1 : 0)
1913            | (firstDayOfWeek << 1)
1914            | (minimalDaysInFirstWeek << 4)
1915            | (zone.hashCode() << 7);
1916        long t = getMillisOf(this);
1917        return (int) t ^ (int)(t >> 32) ^ otheritems;
1918    }
1919
1920    /**
1921     * Returns whether this <code>Calendar</code> represents a time
1922     * before the time represented by the specified
1923     * <code>Object</code>. This method is equivalent to:
1924     * <pre><blockquote>
1925     *         compareTo(when) < 0
1926     * </blockquote></pre>
1927     * if and only if <code>when</code> is a <code>Calendar</code>
1928     * instance. Otherwise, the method returns <code>false</code>.
1929     *
1930     * @param when the <code>Object</code> to be compared
1931     * @return <code>true</code> if the time of this
1932     * <code>Calendar</code> is before the time represented by
1933     * <code>when</code>; <code>false</code> otherwise.
1934     * @see     #compareTo(Calendar)
1935     */
1936    public boolean before(Object when) {
1937        return when instanceof Calendar
1938            && compareTo((Calendar)when) < 0;
1939    }
1940
1941    /**
1942     * Returns whether this <code>Calendar</code> represents a time
1943     * after the time represented by the specified
1944     * <code>Object</code>. This method is equivalent to:
1945     * <pre><blockquote>
1946     *         compareTo(when) > 0
1947     * </blockquote></pre>
1948     * if and only if <code>when</code> is a <code>Calendar</code>
1949     * instance. Otherwise, the method returns <code>false</code>.
1950     *
1951     * @param when the <code>Object</code> to be compared
1952     * @return <code>true</code> if the time of this <code>Calendar</code> is
1953     * after the time represented by <code>when</code>; <code>false</code>
1954     * otherwise.
1955     * @see     #compareTo(Calendar)
1956     */
1957    public boolean after(Object when) {
1958        return when instanceof Calendar
1959            && compareTo((Calendar)when) > 0;
1960    }
1961
1962    /**
1963     * Compares the time values (millisecond offsets from the <a
1964     * href="#Epoch">Epoch</a>) represented by two
1965     * <code>Calendar</code> objects.
1966     *
1967     * @param anotherCalendar the <code>Calendar</code> to be compared.
1968     * @return the value <code>0</code> if the time represented by the argument
1969     * is equal to the time represented by this <code>Calendar</code>; a value
1970     * less than <code>0</code> if the time of this <code>Calendar</code> is
1971     * before the time represented by the argument; and a value greater than
1972     * <code>0</code> if the time of this <code>Calendar</code> is after the
1973     * time represented by the argument.
1974     * @exception NullPointerException if the specified <code>Calendar</code> is
1975     *            <code>null</code>.
1976     * @exception IllegalArgumentException if the time value of the
1977     * specified <code>Calendar</code> object can't be obtained due to
1978     * any invalid calendar values.
1979     * @since   1.5
1980     */
1981    public int compareTo(Calendar anotherCalendar) {
1982        return compareTo(getMillisOf(anotherCalendar));
1983    }
1984
1985    /**
1986     * Adds or subtracts the specified amount of time to the given calendar field,
1987     * based on the calendar's rules. For example, to subtract 5 days from
1988     * the current time of the calendar, you can achieve it by calling:
1989     * <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>.
1990     *
1991     * @param field the calendar field.
1992     * @param amount the amount of date or time to be added to the field.
1993     * @see #roll(int,int)
1994     * @see #set(int,int)
1995     */
1996    abstract public void add(int field, int amount);
1997
1998    /**
1999     * Adds or subtracts (up/down) a single unit of time on the given time
2000     * field without changing larger fields. For example, to roll the current
2001     * date up by one day, you can achieve it by calling:
2002     * <p>roll(Calendar.DATE, true).
2003     * When rolling on the year or Calendar.YEAR field, it will roll the year
2004     * value in the range between 1 and the value returned by calling
2005     * <code>getMaximum(Calendar.YEAR)</code>.
2006     * When rolling on the month or Calendar.MONTH field, other fields like
2007     * date might conflict and, need to be changed. For instance,
2008     * rolling the month on the date 01/31/96 will result in 02/29/96.
2009     * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will
2010     * roll the hour value in the range between 0 and 23, which is zero-based.
2011     *
2012     * @param field the time field.
2013     * @param up indicates if the value of the specified time field is to be
2014     * rolled up or rolled down. Use true if rolling up, false otherwise.
2015     * @see Calendar#add(int,int)
2016     * @see Calendar#set(int,int)
2017     */
2018    abstract public void roll(int field, boolean up);
2019
2020    /**
2021     * Adds the specified (signed) amount to the specified calendar field
2022     * without changing larger fields.  A negative amount means to roll
2023     * down.
2024     *
2025     * <p>NOTE:  This default implementation on <code>Calendar</code> just repeatedly calls the
2026     * version of {@link #roll(int,boolean) roll()} that rolls by one unit.  This may not
2027     * always do the right thing.  For example, if the <code>DAY_OF_MONTH</code> field is 31,
2028     * rolling through February will leave it set to 28.  The <code>GregorianCalendar</code>
2029     * version of this function takes care of this problem.  Other subclasses
2030     * should also provide overrides of this function that do the right thing.
2031     *
2032     * @param field the calendar field.
2033     * @param amount the signed amount to add to the calendar <code>field</code>.
2034     * @since 1.2
2035     * @see #roll(int,boolean)
2036     * @see #add(int,int)
2037     * @see #set(int,int)
2038     */
2039    public void roll(int field, int amount)
2040    {
2041        while (amount > 0) {
2042            roll(field, true);
2043            amount--;
2044        }
2045        while (amount < 0) {
2046            roll(field, false);
2047            amount++;
2048        }
2049    }
2050
2051    /**
2052     * Sets the time zone with the given time zone value.
2053     *
2054     * @param value the given time zone.
2055     */
2056    public void setTimeZone(TimeZone value)
2057    {
2058        zone = value;
2059        sharedZone = false;
2060        /* Recompute the fields from the time using the new zone.  This also
2061         * works if isTimeSet is false (after a call to set()).  In that case
2062         * the time will be computed from the fields using the new zone, then
2063         * the fields will get recomputed from that.  Consider the sequence of
2064         * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
2065         * Is cal set to 1 o'clock EST or 1 o'clock PST?  Answer: PST.  More
2066         * generally, a call to setTimeZone() affects calls to set() BEFORE AND
2067         * AFTER it up to the next call to complete().
2068         */
2069        areAllFieldsSet = areFieldsSet = false;
2070    }
2071
2072    /**
2073     * Gets the time zone.
2074     *
2075     * @return the time zone object associated with this calendar.
2076     */
2077    public TimeZone getTimeZone()
2078    {
2079        // If the TimeZone object is shared by other Calendar instances, then
2080        // create a clone.
2081        if (sharedZone) {
2082            zone = (TimeZone) zone.clone();
2083            sharedZone = false;
2084        }
2085        return zone;
2086    }
2087
2088    /**
2089     * Returns the time zone (without cloning).
2090     */
2091    TimeZone getZone() {
2092        return zone;
2093    }
2094
2095    /**
2096     * Sets the sharedZone flag to <code>shared</code>.
2097     */
2098    void setZoneShared(boolean shared) {
2099        sharedZone = shared;
2100    }
2101
2102    /**
2103     * Specifies whether or not date/time interpretation is to be lenient.  With
2104     * lenient interpretation, a date such as "February 942, 1996" will be
2105     * treated as being equivalent to the 941st day after February 1, 1996.
2106     * With strict (non-lenient) interpretation, such dates will cause an exception to be
2107     * thrown. The default is lenient.
2108     *
2109     * @param lenient <code>true</code> if the lenient mode is to be turned
2110     * on; <code>false</code> if it is to be turned off.
2111     * @see #isLenient()
2112     * @see java.text.DateFormat#setLenient
2113     */
2114    public void setLenient(boolean lenient)
2115    {
2116        this.lenient = lenient;
2117    }
2118
2119    /**
2120     * Tells whether date/time interpretation is to be lenient.
2121     *
2122     * @return <code>true</code> if the interpretation mode of this calendar is lenient;
2123     * <code>false</code> otherwise.
2124     * @see #setLenient(boolean)
2125     */
2126    public boolean isLenient()
2127    {
2128        return lenient;
2129    }
2130
2131    /**
2132     * Sets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
2133     * <code>MONDAY</code> in France.
2134     *
2135     * @param value the given first day of the week.
2136     * @see #getFirstDayOfWeek()
2137     * @see #getMinimalDaysInFirstWeek()
2138     */
2139    public void setFirstDayOfWeek(int value)
2140    {
2141        if (firstDayOfWeek == value) {
2142            return;
2143        }
2144        firstDayOfWeek = value;
2145        invalidateWeekFields();
2146    }
2147
2148    /**
2149     * Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
2150     * <code>MONDAY</code> in France.
2151     *
2152     * @return the first day of the week.
2153     * @see #setFirstDayOfWeek(int)
2154     * @see #getMinimalDaysInFirstWeek()
2155     */
2156    public int getFirstDayOfWeek()
2157    {
2158        return firstDayOfWeek;
2159    }
2160
2161    /**
2162     * Sets what the minimal days required in the first week of the year are;
2163     * For example, if the first week is defined as one that contains the first
2164     * day of the first month of a year, call this method with value 1. If it
2165     * must be a full week, use value 7.
2166     *
2167     * @param value the given minimal days required in the first week
2168     * of the year.
2169     * @see #getMinimalDaysInFirstWeek()
2170     */
2171    public void setMinimalDaysInFirstWeek(int value)
2172    {
2173        if (minimalDaysInFirstWeek == value) {
2174            return;
2175        }
2176        minimalDaysInFirstWeek = value;
2177        invalidateWeekFields();
2178    }
2179
2180    /**
2181     * Gets what the minimal days required in the first week of the year are;
2182     * e.g., if the first week is defined as one that contains the first day
2183     * of the first month of a year, this method returns 1. If
2184     * the minimal days required must be a full week, this method
2185     * returns 7.
2186     *
2187     * @return the minimal days required in the first week of the year.
2188     * @see #setMinimalDaysInFirstWeek(int)
2189     */
2190    public int getMinimalDaysInFirstWeek()
2191    {
2192        return minimalDaysInFirstWeek;
2193    }
2194
2195    /**
2196     * Returns whether this {@code Calendar} supports week dates.
2197     *
2198     * <p>The default implementation of this method returns {@code false}.
2199     *
2200     * @return {@code true} if this {@code Calendar} supports week dates;
2201     *         {@code false} otherwise.
2202     * @see #getWeekYear()
2203     * @see #setWeekDate(int,int,int)
2204     * @see #getWeeksInWeekYear()
2205     * @since 1.7
2206     */
2207    public boolean isWeekDateSupported() {
2208        return false;
2209    }
2210
2211    /**
2212     * Returns the week year represented by this {@code Calendar}. The
2213     * week year is in sync with the week cycle. The {@linkplain
2214     * #getFirstDayOfWeek() first day of the first week} is the first
2215     * day of the week year.
2216     *
2217     * <p>The default implementation of this method throws an
2218     * {@link UnsupportedOperationException}.
2219     *
2220     * @return the week year of this {@code Calendar}
2221     * @exception UnsupportedOperationException
2222     *            if any week year numbering isn't supported
2223     *            in this {@code Calendar}.
2224     * @see #isWeekDateSupported()
2225     * @see #getFirstDayOfWeek()
2226     * @see #getMinimalDaysInFirstWeek()
2227     * @since 1.7
2228     */
2229    public int getWeekYear() {
2230        throw new UnsupportedOperationException();
2231    }
2232
2233    /**
2234     * Sets the date of this {@code Calendar} with the the given date
2235     * specifiers - week year, week of year, and day of week.
2236     *
2237     * <p>Unlike the {@code set} method, all of the calendar fields
2238     * and {@code time} values are calculated upon return.
2239     *
2240     * <p>If {@code weekOfYear} is out of the valid week-of-year range
2241     * in {@code weekYear}, the {@code weekYear} and {@code
2242     * weekOfYear} values are adjusted in lenient mode, or an {@code
2243     * IllegalArgumentException} is thrown in non-lenient mode.
2244     *
2245     * <p>The default implementation of this method throws an
2246     * {@code UnsupportedOperationException}.
2247     *
2248     * @param weekYear   the week year
2249     * @param weekOfYear the week number based on {@code weekYear}
2250     * @param dayOfWeek  the day of week value: one of the constants
2251     *                   for the {@link #DAY_OF_WEEK} field: {@link
2252     *                   #SUNDAY}, ..., {@link #SATURDAY}.
2253     * @exception IllegalArgumentException
2254     *            if any of the given date specifiers is invalid
2255     *            or any of the calendar fields are inconsistent
2256     *            with the given date specifiers in non-lenient mode
2257     * @exception UnsupportedOperationException
2258     *            if any week year numbering isn't supported in this
2259     *            {@code Calendar}.
2260     * @see #isWeekDateSupported()
2261     * @see #getFirstDayOfWeek()
2262     * @see #getMinimalDaysInFirstWeek()
2263     * @since 1.7
2264     */
2265    public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
2266        throw new UnsupportedOperationException();
2267    }
2268
2269    /**
2270     * Returns the number of weeks in the week year represented by this
2271     * {@code Calendar}.
2272     *
2273     * <p>The default implementation of this method throws an
2274     * {@code UnsupportedOperationException}.
2275     *
2276     * @return the number of weeks in the week year.
2277     * @exception UnsupportedOperationException
2278     *            if any week year numbering isn't supported in this
2279     *            {@code Calendar}.
2280     * @see #WEEK_OF_YEAR
2281     * @see #isWeekDateSupported()
2282     * @see #getWeekYear()
2283     * @see #getActualMaximum(int)
2284     * @since 1.7
2285     */
2286    public int getWeeksInWeekYear() {
2287        throw new UnsupportedOperationException();
2288    }
2289
2290    /**
2291     * Returns the minimum value for the given calendar field of this
2292     * <code>Calendar</code> instance. The minimum value is defined as
2293     * the smallest value returned by the {@link #get(int) get} method
2294     * for any possible time value.  The minimum value depends on
2295     * calendar system specific parameters of the instance.
2296     *
2297     * @param field the calendar field.
2298     * @return the minimum value for the given calendar field.
2299     * @see #getMaximum(int)
2300     * @see #getGreatestMinimum(int)
2301     * @see #getLeastMaximum(int)
2302     * @see #getActualMinimum(int)
2303     * @see #getActualMaximum(int)
2304     */
2305    abstract public int getMinimum(int field);
2306
2307    /**
2308     * Returns the maximum value for the given calendar field of this
2309     * <code>Calendar</code> instance. The maximum value is defined as
2310     * the largest value returned by the {@link #get(int) get} method
2311     * for any possible time value. The maximum value depends on
2312     * calendar system specific parameters of the instance.
2313     *
2314     * @param field the calendar field.
2315     * @return the maximum value for the given calendar field.
2316     * @see #getMinimum(int)
2317     * @see #getGreatestMinimum(int)
2318     * @see #getLeastMaximum(int)
2319     * @see #getActualMinimum(int)
2320     * @see #getActualMaximum(int)
2321     */
2322    abstract public int getMaximum(int field);
2323
2324    /**
2325     * Returns the highest minimum value for the given calendar field
2326     * of this <code>Calendar</code> instance. The highest minimum
2327     * value is defined as the largest value returned by {@link
2328     * #getActualMinimum(int)} for any possible time value. The
2329     * greatest minimum value depends on calendar system specific
2330     * parameters of the instance.
2331     *
2332     * @param field the calendar field.
2333     * @return the highest minimum value for the given calendar field.
2334     * @see #getMinimum(int)
2335     * @see #getMaximum(int)
2336     * @see #getLeastMaximum(int)
2337     * @see #getActualMinimum(int)
2338     * @see #getActualMaximum(int)
2339     */
2340    abstract public int getGreatestMinimum(int field);
2341
2342    /**
2343     * Returns the lowest maximum value for the given calendar field
2344     * of this <code>Calendar</code> instance. The lowest maximum
2345     * value is defined as the smallest value returned by {@link
2346     * #getActualMaximum(int)} for any possible time value. The least
2347     * maximum value depends on calendar system specific parameters of
2348     * the instance. For example, a <code>Calendar</code> for the
2349     * Gregorian calendar system returns 28 for the
2350     * <code>DAY_OF_MONTH</code> field, because the 28th is the last
2351     * day of the shortest month of this calendar, February in a
2352     * common year.
2353     *
2354     * @param field the calendar field.
2355     * @return the lowest maximum value for the given calendar field.
2356     * @see #getMinimum(int)
2357     * @see #getMaximum(int)
2358     * @see #getGreatestMinimum(int)
2359     * @see #getActualMinimum(int)
2360     * @see #getActualMaximum(int)
2361     */
2362    abstract public int getLeastMaximum(int field);
2363
2364    /**
2365     * Returns the minimum value that the specified calendar field
2366     * could have, given the time value of this <code>Calendar</code>.
2367     *
2368     * <p>The default implementation of this method uses an iterative
2369     * algorithm to determine the actual minimum value for the
2370     * calendar field. Subclasses should, if possible, override this
2371     * with a more efficient implementation - in many cases, they can
2372     * simply return <code>getMinimum()</code>.
2373     *
2374     * @param field the calendar field
2375     * @return the minimum of the given calendar field for the time
2376     * value of this <code>Calendar</code>
2377     * @see #getMinimum(int)
2378     * @see #getMaximum(int)
2379     * @see #getGreatestMinimum(int)
2380     * @see #getLeastMaximum(int)
2381     * @see #getActualMaximum(int)
2382     * @since 1.2
2383     */
2384    public int getActualMinimum(int field) {
2385        int fieldValue = getGreatestMinimum(field);
2386        int endValue = getMinimum(field);
2387
2388        // if we know that the minimum value is always the same, just return it
2389        if (fieldValue == endValue) {
2390            return fieldValue;
2391        }
2392
2393        // clone the calendar so we don't mess with the real one, and set it to
2394        // accept anything for the field values
2395        Calendar work = (Calendar)this.clone();
2396        work.setLenient(true);
2397
2398        // now try each value from getLeastMaximum() to getMaximum() one by one until
2399        // we get a value that normalizes to another value.  The last value that
2400        // normalizes to itself is the actual minimum for the current date
2401        int result = fieldValue;
2402
2403        do {
2404            work.set(field, fieldValue);
2405            if (work.get(field) != fieldValue) {
2406                break;
2407            } else {
2408                result = fieldValue;
2409                fieldValue--;
2410            }
2411        } while (fieldValue >= endValue);
2412
2413        return result;
2414    }
2415
2416    /**
2417     * Returns the maximum value that the specified calendar field
2418     * could have, given the time value of this
2419     * <code>Calendar</code>. For example, the actual maximum value of
2420     * the <code>MONTH</code> field is 12 in some years, and 13 in
2421     * other years in the Hebrew calendar system.
2422     *
2423     * <p>The default implementation of this method uses an iterative
2424     * algorithm to determine the actual maximum value for the
2425     * calendar field. Subclasses should, if possible, override this
2426     * with a more efficient implementation.
2427     *
2428     * @param field the calendar field
2429     * @return the maximum of the given calendar field for the time
2430     * value of this <code>Calendar</code>
2431     * @see #getMinimum(int)
2432     * @see #getMaximum(int)
2433     * @see #getGreatestMinimum(int)
2434     * @see #getLeastMaximum(int)
2435     * @see #getActualMinimum(int)
2436     * @since 1.2
2437     */
2438    public int getActualMaximum(int field) {
2439        int fieldValue = getLeastMaximum(field);
2440        int endValue = getMaximum(field);
2441
2442        // if we know that the maximum value is always the same, just return it.
2443        if (fieldValue == endValue) {
2444            return fieldValue;
2445        }
2446
2447        // clone the calendar so we don't mess with the real one, and set it to
2448        // accept anything for the field values.
2449        Calendar work = (Calendar)this.clone();
2450        work.setLenient(true);
2451
2452        // if we're counting weeks, set the day of the week to Sunday.  We know the
2453        // last week of a month or year will contain the first day of the week.
2454        if (field == WEEK_OF_YEAR || field == WEEK_OF_MONTH)
2455            work.set(DAY_OF_WEEK, firstDayOfWeek);
2456
2457        // now try each value from getLeastMaximum() to getMaximum() one by one until
2458        // we get a value that normalizes to another value.  The last value that
2459        // normalizes to itself is the actual maximum for the current date
2460        int result = fieldValue;
2461
2462        do {
2463            work.set(field, fieldValue);
2464            if (work.get(field) != fieldValue) {
2465                break;
2466            } else {
2467                result = fieldValue;
2468                fieldValue++;
2469            }
2470        } while (fieldValue <= endValue);
2471
2472        return result;
2473    }
2474
2475    /**
2476     * Creates and returns a copy of this object.
2477     *
2478     * @return a copy of this object.
2479     */
2480    public Object clone()
2481    {
2482        try {
2483            Calendar other = (Calendar) super.clone();
2484
2485            other.fields = new int[FIELD_COUNT];
2486            other.isSet = new boolean[FIELD_COUNT];
2487            other.stamp = new int[FIELD_COUNT];
2488            for (int i = 0; i < FIELD_COUNT; i++) {
2489                other.fields[i] = fields[i];
2490                other.stamp[i] = stamp[i];
2491                other.isSet[i] = isSet[i];
2492            }
2493            other.zone = (TimeZone) zone.clone();
2494            return other;
2495        }
2496        catch (CloneNotSupportedException e) {
2497            // this shouldn't happen, since we are Cloneable
2498            throw new InternalError();
2499        }
2500    }
2501
2502    private static final String[] FIELD_NAME = {
2503        "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH",
2504        "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR",
2505        "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET",
2506        "DST_OFFSET"
2507    };
2508
2509    /**
2510     * Returns the name of the specified calendar field.
2511     *
2512     * @param field the calendar field
2513     * @return the calendar field name
2514     * @exception IndexOutOfBoundsException if <code>field</code> is negative,
2515     * equal to or greater then <code>FIELD_COUNT</code>.
2516     */
2517    static final String getFieldName(int field) {
2518        return FIELD_NAME[field];
2519    }
2520
2521    /**
2522     * Return a string representation of this calendar. This method
2523     * is intended to be used only for debugging purposes, and the
2524     * format of the returned string may vary between implementations.
2525     * The returned string may be empty but may not be <code>null</code>.
2526     *
2527     * @return  a string representation of this calendar.
2528     */
2529    public String toString() {
2530        // NOTE: BuddhistCalendar.toString() interprets the string
2531        // produced by this method so that the Gregorian year number
2532        // is substituted by its B.E. year value. It relies on
2533        // "...,YEAR=<year>,..." or "...,YEAR=?,...".
2534        StringBuilder buffer = new StringBuilder(800);
2535        buffer.append(getClass().getName()).append('[');
2536        appendValue(buffer, "time", isTimeSet, time);
2537        buffer.append(",areFieldsSet=").append(areFieldsSet);
2538        buffer.append(",areAllFieldsSet=").append(areAllFieldsSet);
2539        buffer.append(",lenient=").append(lenient);
2540        buffer.append(",zone=").append(zone);
2541        appendValue(buffer, ",firstDayOfWeek", true, (long) firstDayOfWeek);
2542        appendValue(buffer, ",minimalDaysInFirstWeek", true, (long) minimalDaysInFirstWeek);
2543        for (int i = 0; i < FIELD_COUNT; ++i) {
2544            buffer.append(',');
2545            appendValue(buffer, FIELD_NAME[i], isSet(i), (long) fields[i]);
2546        }
2547        buffer.append(']');
2548        return buffer.toString();
2549    }
2550
2551    // =======================privates===============================
2552
2553    private static final void appendValue(StringBuilder sb, String item, boolean valid, long value) {
2554        sb.append(item).append('=');
2555        if (valid) {
2556            sb.append(value);
2557        } else {
2558            sb.append('?');
2559        }
2560    }
2561
2562    /**
2563     * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.
2564     * They are used to figure out the week count for a specific date for
2565     * a given locale. These must be set when a Calendar is constructed.
2566     * @param desiredLocale the given locale.
2567     */
2568    private void setWeekCountData(Locale desiredLocale)
2569    {
2570        /* try to get the Locale data from the cache */
2571        int[] data = cachedLocaleData.get(desiredLocale);
2572        if (data == null) {  /* cache miss */
2573            LocaleData localeData = LocaleData.get(desiredLocale);
2574            data = new int[2];
2575            data[0] = localeData.firstDayOfWeek.intValue();
2576            data[1] = localeData.minimalDaysInFirstWeek.intValue();
2577            cachedLocaleData.putIfAbsent(desiredLocale, data);
2578        }
2579        firstDayOfWeek = data[0];
2580        minimalDaysInFirstWeek = data[1];
2581    }
2582
2583    /**
2584     * Recomputes the time and updates the status fields isTimeSet
2585     * and areFieldsSet.  Callers should check isTimeSet and only
2586     * call this method if isTimeSet is false.
2587     */
2588    private void updateTime() {
2589        computeTime();
2590        // The areFieldsSet and areAllFieldsSet values are no longer
2591        // controlled here (as of 1.5).
2592        isTimeSet = true;
2593    }
2594
2595    private int compareTo(long t) {
2596        long thisTime = getMillisOf(this);
2597        return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
2598    }
2599
2600    private static final long getMillisOf(Calendar calendar) {
2601        if (calendar.isTimeSet) {
2602            return calendar.time;
2603        }
2604        Calendar cal = (Calendar) calendar.clone();
2605        cal.setLenient(true);
2606        return cal.getTimeInMillis();
2607    }
2608
2609    /**
2610     * Adjusts the stamp[] values before nextStamp overflow. nextStamp
2611     * is set to the next stamp value upon the return.
2612     */
2613    private final void adjustStamp() {
2614        int max = MINIMUM_USER_STAMP;
2615        int newStamp = MINIMUM_USER_STAMP;
2616
2617        for (;;) {
2618            int min = Integer.MAX_VALUE;
2619            for (int i = 0; i < stamp.length; i++) {
2620                int v = stamp[i];
2621                if (v >= newStamp && min > v) {
2622                    min = v;
2623                }
2624                if (max < v) {
2625                    max = v;
2626                }
2627            }
2628            if (max != min && min == Integer.MAX_VALUE) {
2629                break;
2630            }
2631            for (int i = 0; i < stamp.length; i++) {
2632                if (stamp[i] == min) {
2633                    stamp[i] = newStamp;
2634                }
2635            }
2636            newStamp++;
2637            if (min == max) {
2638                break;
2639            }
2640        }
2641        nextStamp = newStamp;
2642    }
2643
2644    /**
2645     * Sets the WEEK_OF_MONTH and WEEK_OF_YEAR fields to new values with the
2646     * new parameter value if they have been calculated internally.
2647     */
2648    private void invalidateWeekFields()
2649    {
2650        if (stamp[WEEK_OF_MONTH] != COMPUTED &&
2651            stamp[WEEK_OF_YEAR] != COMPUTED) {
2652            return;
2653        }
2654
2655        // We have to check the new values of these fields after changing
2656        // firstDayOfWeek and/or minimalDaysInFirstWeek. If the field values
2657        // have been changed, then set the new values. (4822110)
2658        Calendar cal = (Calendar) clone();
2659        cal.setLenient(true);
2660        cal.clear(WEEK_OF_MONTH);
2661        cal.clear(WEEK_OF_YEAR);
2662
2663        if (stamp[WEEK_OF_MONTH] == COMPUTED) {
2664            int weekOfMonth = cal.get(WEEK_OF_MONTH);
2665            if (fields[WEEK_OF_MONTH] != weekOfMonth) {
2666                fields[WEEK_OF_MONTH] = weekOfMonth;
2667            }
2668        }
2669
2670        if (stamp[WEEK_OF_YEAR] == COMPUTED) {
2671            int weekOfYear = cal.get(WEEK_OF_YEAR);
2672            if (fields[WEEK_OF_YEAR] != weekOfYear) {
2673                fields[WEEK_OF_YEAR] = weekOfYear;
2674            }
2675        }
2676    }
2677
2678    /**
2679     * Save the state of this object to a stream (i.e., serialize it).
2680     *
2681     * Ideally, <code>Calendar</code> would only write out its state data and
2682     * the current time, and not write any field data out, such as
2683     * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>,
2684     * and <code>isSet[]</code>.  <code>nextStamp</code> also should not be part
2685     * of the persistent state. Unfortunately, this didn't happen before JDK 1.1
2686     * shipped. To be compatible with JDK 1.1, we will always have to write out
2687     * the field values and state flags.  However, <code>nextStamp</code> can be
2688     * removed from the serialization stream; this will probably happen in the
2689     * near future.
2690     */
2691    private synchronized void writeObject(ObjectOutputStream stream)
2692         throws IOException
2693    {
2694        // Try to compute the time correctly, for the future (stream
2695        // version 2) in which we don't write out fields[] or isSet[].
2696        if (!isTimeSet) {
2697            try {
2698                updateTime();
2699            }
2700            catch (IllegalArgumentException e) {}
2701        }
2702
2703        // Write out the 1.1 FCS object.
2704        stream.defaultWriteObject();
2705    }
2706
2707    private static class CalendarAccessControlContext {
2708        private static final AccessControlContext INSTANCE;
2709        static {
2710            RuntimePermission perm = new RuntimePermission("accessClassInPackage.sun.util.calendar");
2711            PermissionCollection perms = perm.newPermissionCollection();
2712            perms.add(perm);
2713            INSTANCE = new AccessControlContext(new ProtectionDomain[] {
2714                                                    new ProtectionDomain(null, perms)
2715                                                });
2716        }
2717    }
2718
2719    /**
2720     * Reconstitutes this object from a stream (i.e., deserialize it).
2721     */
2722    private void readObject(ObjectInputStream stream)
2723         throws IOException, ClassNotFoundException
2724    {
2725        final ObjectInputStream input = stream;
2726        input.defaultReadObject();
2727
2728        stamp = new int[FIELD_COUNT];
2729
2730        // Starting with version 2 (not implemented yet), we expect that
2731        // fields[], isSet[], isTimeSet, and areFieldsSet may not be
2732        // streamed out anymore.  We expect 'time' to be correct.
2733        if (serialVersionOnStream >= 2)
2734        {
2735            isTimeSet = true;
2736            if (fields == null) fields = new int[FIELD_COUNT];
2737            if (isSet == null) isSet = new boolean[FIELD_COUNT];
2738        }
2739        else if (serialVersionOnStream >= 0)
2740        {
2741            for (int i=0; i<FIELD_COUNT; ++i)
2742                stamp[i] = isSet[i] ? COMPUTED : UNSET;
2743        }
2744
2745        serialVersionOnStream = currentSerialVersion;
2746
2747        // If the deserialized object has a SimpleTimeZone, try to
2748        // replace it with a ZoneInfo equivalent (as of 1.4) in order
2749        // to be compatible with the SimpleTimeZone-based
2750        // implementation as much as possible.
2751        if (zone instanceof SimpleTimeZone) {
2752            String id = zone.getID();
2753            TimeZone tz = TimeZone.getTimeZone(id);
2754            if (tz != null && tz.hasSameRules(zone) && tz.getID().equals(id)) {
2755                zone = tz;
2756            }
2757        }
2758    }
2759}
2760