Calendar.java revision 12745:f068a4ffddd2
1/*
2 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26/*
27 * (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved
28 * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
29 *
30 *   The original version of this source code and documentation is copyrighted
31 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
32 * materials are provided under terms of a License Agreement between Taligent
33 * and Sun. This technology is protected by multiple US and International
34 * patents. This notice and attribution to Taligent may not be removed.
35 *   Taligent is a registered trademark of Taligent, Inc.
36 *
37 */
38
39package java.util;
40
41import java.io.IOException;
42import java.io.ObjectInputStream;
43import java.io.ObjectOutputStream;
44import java.io.OptionalDataException;
45import java.io.Serializable;
46import java.security.AccessControlContext;
47import java.security.AccessController;
48import java.security.PermissionCollection;
49import java.security.PrivilegedActionException;
50import java.security.PrivilegedExceptionAction;
51import java.security.ProtectionDomain;
52import java.text.DateFormat;
53import java.text.DateFormatSymbols;
54import java.time.Instant;
55import java.util.concurrent.ConcurrentHashMap;
56import java.util.concurrent.ConcurrentMap;
57import sun.util.BuddhistCalendar;
58import sun.util.calendar.ZoneInfo;
59import sun.util.locale.provider.CalendarDataUtility;
60import sun.util.locale.provider.LocaleProviderAdapter;
61import sun.util.spi.CalendarProvider;
62
63/**
64 * The <code>Calendar</code> class is an abstract class that provides methods
65 * for converting between a specific instant in time and a set of {@link
66 * #fields calendar fields} such as <code>YEAR</code>, <code>MONTH</code>,
67 * <code>DAY_OF_MONTH</code>, <code>HOUR</code>, and so on, and for
68 * manipulating the calendar fields, such as getting the date of the next
69 * week. An instant in time can be represented by a millisecond value that is
70 * an offset from the <a name="Epoch"><em>Epoch</em></a>, January 1, 1970
71 * 00:00:00.000 GMT (Gregorian).
72 *
73 * <p>The class also provides additional fields and methods for
74 * implementing a concrete calendar system outside the package. Those
75 * fields and methods are defined as <code>protected</code>.
76 *
77 * <p>
78 * Like other locale-sensitive classes, <code>Calendar</code> provides a
79 * class method, <code>getInstance</code>, for getting a generally useful
80 * object of this type. <code>Calendar</code>'s <code>getInstance</code> method
81 * returns a <code>Calendar</code> object whose
82 * calendar fields have been initialized with the current date and time:
83 * <blockquote>
84 * <pre>
85 *     Calendar rightNow = Calendar.getInstance();
86 * </pre>
87 * </blockquote>
88 *
89 * <p>A <code>Calendar</code> object can produce all the calendar field values
90 * needed to implement the date-time formatting for a particular language and
91 * calendar style (for example, Japanese-Gregorian, Japanese-Traditional).
92 * <code>Calendar</code> defines the range of values returned by
93 * certain calendar fields, as well as their meaning.  For example,
94 * the first month of the calendar system has value <code>MONTH ==
95 * JANUARY</code> for all calendars.  Other values are defined by the
96 * concrete subclass, such as <code>ERA</code>.  See individual field
97 * documentation and subclass documentation for details.
98 *
99 * <h3>Getting and Setting Calendar Field Values</h3>
100 *
101 * <p>The calendar field values can be set by calling the <code>set</code>
102 * methods. Any field values set in a <code>Calendar</code> will not be
103 * interpreted until it needs to calculate its time value (milliseconds from
104 * the Epoch) or values of the calendar fields. Calling the
105 * <code>get</code>, <code>getTimeInMillis</code>, <code>getTime</code>,
106 * <code>add</code> and <code>roll</code> involves such calculation.
107 *
108 * <h4>Leniency</h4>
109 *
110 * <p><code>Calendar</code> has two modes for interpreting the calendar
111 * fields, <em>lenient</em> and <em>non-lenient</em>.  When a
112 * <code>Calendar</code> is in lenient mode, it accepts a wider range of
113 * calendar field values than it produces.  When a <code>Calendar</code>
114 * recomputes calendar field values for return by <code>get()</code>, all of
115 * the calendar fields are normalized. For example, a lenient
116 * <code>GregorianCalendar</code> interprets <code>MONTH == JANUARY</code>,
117 * <code>DAY_OF_MONTH == 32</code> as February 1.
118
119 * <p>When a <code>Calendar</code> is in non-lenient mode, it throws an
120 * exception if there is any inconsistency in its calendar fields. For
121 * example, a <code>GregorianCalendar</code> always produces
122 * <code>DAY_OF_MONTH</code> values between 1 and the length of the month. A
123 * non-lenient <code>GregorianCalendar</code> throws an exception upon
124 * calculating its time or calendar field values if any out-of-range field
125 * value has been set.
126 *
127 * <h4><a name="first_week">First Week</a></h4>
128 *
129 * <code>Calendar</code> defines a locale-specific seven day week using two
130 * parameters: the first day of the week and the minimal days in first week
131 * (from 1 to 7).  These numbers are taken from the locale resource data when a
132 * <code>Calendar</code> is constructed.  They may also be specified explicitly
133 * through the methods for setting their values.
134 *
135 * <p>When setting or getting the <code>WEEK_OF_MONTH</code> or
136 * <code>WEEK_OF_YEAR</code> fields, <code>Calendar</code> must determine the
137 * first week of the month or year as a reference point.  The first week of a
138 * month or year is defined as the earliest seven day period beginning on
139 * <code>getFirstDayOfWeek()</code> and containing at least
140 * <code>getMinimalDaysInFirstWeek()</code> days of that month or year.  Weeks
141 * numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow
142 * it.  Note that the normalized numbering returned by <code>get()</code> may be
143 * different.  For example, a specific <code>Calendar</code> subclass may
144 * designate the week before week 1 of a year as week <code><i>n</i></code> of
145 * the previous year.
146 *
147 * <h4>Calendar Fields Resolution</h4>
148 *
149 * When computing a date and time from the calendar fields, there
150 * may be insufficient information for the computation (such as only
151 * year and month with no day of month), or there may be inconsistent
152 * information (such as Tuesday, July 15, 1996 (Gregorian) -- July 15,
153 * 1996 is actually a Monday). <code>Calendar</code> will resolve
154 * calendar field values to determine the date and time in the
155 * following way.
156 *
157 * <p><a name="resolution">If there is any conflict in calendar field values,
158 * <code>Calendar</code> gives priorities to calendar fields that have been set
159 * more recently.</a> The following are the default combinations of the
160 * calendar fields. The most recent combination, as determined by the
161 * most recently set single field, will be used.
162 *
163 * <p><a name="date_resolution">For the date fields</a>:
164 * <blockquote>
165 * <pre>
166 * YEAR + MONTH + DAY_OF_MONTH
167 * YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
168 * YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
169 * YEAR + DAY_OF_YEAR
170 * YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
171 * </pre></blockquote>
172 *
173 * <a name="time_resolution">For the time of day fields</a>:
174 * <blockquote>
175 * <pre>
176 * HOUR_OF_DAY
177 * AM_PM + HOUR
178 * </pre></blockquote>
179 *
180 * <p>If there are any calendar fields whose values haven't been set in the selected
181 * field combination, <code>Calendar</code> uses their default values. The default
182 * value of each field may vary by concrete calendar systems. For example, in
183 * <code>GregorianCalendar</code>, the default of a field is the same as that
184 * of the start of the Epoch: i.e., <code>YEAR = 1970</code>, <code>MONTH =
185 * JANUARY</code>, <code>DAY_OF_MONTH = 1</code>, etc.
186 *
187 * <p>
188 * <strong>Note:</strong> There are certain possible ambiguities in
189 * interpretation of certain singular times, which are resolved in the
190 * following ways:
191 * <ol>
192 *     <li> 23:59 is the last minute of the day and 00:00 is the first
193 *          minute of the next day. Thus, 23:59 on Dec 31, 1999 &lt; 00:00 on
194 *          Jan 1, 2000 &lt; 00:01 on Jan 1, 2000.
195 *
196 *     <li> Although historically not precise, midnight also belongs to "am",
197 *          and noon belongs to "pm", so on the same day,
198 *          12:00 am (midnight) &lt; 12:01 am, and 12:00 pm (noon) &lt; 12:01 pm
199 * </ol>
200 *
201 * <p>
202 * The date or time format strings are not part of the definition of a
203 * calendar, as those must be modifiable or overridable by the user at
204 * runtime. Use {@link DateFormat}
205 * to format dates.
206 *
207 * <h4>Field Manipulation</h4>
208 *
209 * The calendar fields can be changed using three methods:
210 * <code>set()</code>, <code>add()</code>, and <code>roll()</code>.
211 *
212 * <p><strong><code>set(f, value)</code></strong> changes calendar field
213 * <code>f</code> to <code>value</code>.  In addition, it sets an
214 * internal member variable to indicate that calendar field <code>f</code> has
215 * been changed. Although calendar field <code>f</code> is changed immediately,
216 * the calendar's time value in milliseconds is not recomputed until the next call to
217 * <code>get()</code>, <code>getTime()</code>, <code>getTimeInMillis()</code>,
218 * <code>add()</code>, or <code>roll()</code> is made. Thus, multiple calls to
219 * <code>set()</code> do not trigger multiple, unnecessary
220 * computations. As a result of changing a calendar field using
221 * <code>set()</code>, other calendar fields may also change, depending on the
222 * calendar field, the calendar field value, and the calendar system. In addition,
223 * <code>get(f)</code> will not necessarily return <code>value</code> set by
224 * the call to the <code>set</code> method
225 * after the calendar fields have been recomputed. The specifics are determined by
226 * the concrete calendar class.</p>
227 *
228 * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
229 * originally set to August 31, 1999. Calling <code>set(Calendar.MONTH,
230 * Calendar.SEPTEMBER)</code> sets the date to September 31,
231 * 1999. This is a temporary internal representation that resolves to
232 * October 1, 1999 if <code>getTime()</code>is then called. However, a
233 * call to <code>set(Calendar.DAY_OF_MONTH, 30)</code> before the call to
234 * <code>getTime()</code> sets the date to September 30, 1999, since
235 * no recomputation occurs after <code>set()</code> itself.</p>
236 *
237 * <p><strong><code>add(f, delta)</code></strong> adds <code>delta</code>
238 * to field <code>f</code>.  This is equivalent to calling <code>set(f,
239 * get(f) + delta)</code> with two adjustments:</p>
240 *
241 * <blockquote>
242 *   <p><strong>Add rule 1</strong>. The value of field <code>f</code>
243 *   after the call minus the value of field <code>f</code> before the
244 *   call is <code>delta</code>, modulo any overflow that has occurred in
245 *   field <code>f</code>. Overflow occurs when a field value exceeds its
246 *   range and, as a result, the next larger field is incremented or
247 *   decremented and the field value is adjusted back into its range.</p>
248 *
249 *   <p><strong>Add rule 2</strong>. If a smaller field is expected to be
250 *   invariant, but it is impossible for it to be equal to its
251 *   prior value because of changes in its minimum or maximum after field
252 *   <code>f</code> is changed or other constraints, such as time zone
253 *   offset changes, then its value is adjusted to be as close
254 *   as possible to its expected value. A smaller field represents a
255 *   smaller unit of time. <code>HOUR</code> is a smaller field than
256 *   <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields
257 *   that are not expected to be invariant. The calendar system
258 *   determines what fields are expected to be invariant.</p>
259 * </blockquote>
260 *
261 * <p>In addition, unlike <code>set()</code>, <code>add()</code> forces
262 * an immediate recomputation of the calendar's milliseconds and all
263 * fields.</p>
264 *
265 * <p><em>Example</em>: Consider a <code>GregorianCalendar</code>
266 * originally set to August 31, 1999. Calling <code>add(Calendar.MONTH,
267 * 13)</code> sets the calendar to September 30, 2000. <strong>Add rule
268 * 1</strong> sets the <code>MONTH</code> field to September, since
269 * adding 13 months to August gives September of the next year. Since
270 * <code>DAY_OF_MONTH</code> cannot be 31 in September in a
271 * <code>GregorianCalendar</code>, <strong>add rule 2</strong> sets the
272 * <code>DAY_OF_MONTH</code> to 30, the closest possible value. Although
273 * it is a smaller field, <code>DAY_OF_WEEK</code> is not adjusted by
274 * rule 2, since it is expected to change when the month changes in a
275 * <code>GregorianCalendar</code>.</p>
276 *
277 * <p><strong><code>roll(f, delta)</code></strong> adds
278 * <code>delta</code> to field <code>f</code> without changing larger
279 * fields. This is equivalent to calling <code>add(f, delta)</code> with
280 * the following adjustment:</p>
281 *
282 * <blockquote>
283 *   <p><strong>Roll rule</strong>. Larger fields are unchanged after the
284 *   call. A larger field represents a larger unit of
285 *   time. <code>DAY_OF_MONTH</code> is a larger field than
286 *   <code>HOUR</code>.</p>
287 * </blockquote>
288 *
289 * <p><em>Example</em>: See {@link java.util.GregorianCalendar#roll(int, int)}.
290 *
291 * <p><strong>Usage model</strong>. To motivate the behavior of
292 * <code>add()</code> and <code>roll()</code>, consider a user interface
293 * component with increment and decrement buttons for the month, day, and
294 * year, and an underlying <code>GregorianCalendar</code>. If the
295 * interface reads January 31, 1999 and the user presses the month
296 * increment button, what should it read? If the underlying
297 * implementation uses <code>set()</code>, it might read March 3, 1999. A
298 * better result would be February 28, 1999. Furthermore, if the user
299 * presses the month increment button again, it should read March 31,
300 * 1999, not March 28, 1999. By saving the original date and using either
301 * <code>add()</code> or <code>roll()</code>, depending on whether larger
302 * fields should be affected, the user interface can behave as most users
303 * will intuitively expect.</p>
304 *
305 * @see          java.lang.System#currentTimeMillis()
306 * @see          Date
307 * @see          GregorianCalendar
308 * @see          TimeZone
309 * @see          java.text.DateFormat
310 * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
311 * @since 1.1
312 */
313public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> {
314
315    // Data flow in Calendar
316    // ---------------------
317
318    // The current time is represented in two ways by Calendar: as UTC
319    // milliseconds from the epoch (1 January 1970 0:00 UTC), and as local
320    // fields such as MONTH, HOUR, AM_PM, etc.  It is possible to compute the
321    // millis from the fields, and vice versa.  The data needed to do this
322    // conversion is encapsulated by a TimeZone object owned by the Calendar.
323    // The data provided by the TimeZone object may also be overridden if the
324    // user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class
325    // keeps track of what information was most recently set by the caller, and
326    // uses that to compute any other information as needed.
327
328    // If the user sets the fields using set(), the data flow is as follows.
329    // This is implemented by the Calendar subclass's computeTime() method.
330    // During this process, certain fields may be ignored.  The disambiguation
331    // algorithm for resolving which fields to pay attention to is described
332    // in the class documentation.
333
334    //   local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
335    //           |
336    //           | Using Calendar-specific algorithm
337    //           V
338    //   local standard millis
339    //           |
340    //           | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET
341    //           V
342    //   UTC millis (in time data member)
343
344    // If the user sets the UTC millis using setTime() or setTimeInMillis(),
345    // the data flow is as follows.  This is implemented by the Calendar
346    // subclass's computeFields() method.
347
348    //   UTC millis (in time data member)
349    //           |
350    //           | Using TimeZone getOffset()
351    //           V
352    //   local standard millis
353    //           |
354    //           | Using Calendar-specific algorithm
355    //           V
356    //   local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
357
358    // In general, a round trip from fields, through local and UTC millis, and
359    // back out to fields is made when necessary.  This is implemented by the
360    // complete() method.  Resolving a partial set of fields into a UTC millis
361    // value allows all remaining fields to be generated from that value.  If
362    // the Calendar is lenient, the fields are also renormalized to standard
363    // ranges when they are regenerated.
364
365    /**
366     * Field number for <code>get</code> and <code>set</code> indicating the
367     * era, e.g., AD or BC in the Julian calendar. This is a calendar-specific
368     * value; see subclass documentation.
369     *
370     * @see GregorianCalendar#AD
371     * @see GregorianCalendar#BC
372     */
373    public static final int ERA = 0;
374
375    /**
376     * Field number for <code>get</code> and <code>set</code> indicating the
377     * year. This is a calendar-specific value; see subclass documentation.
378     */
379    public static final int YEAR = 1;
380
381    /**
382     * Field number for <code>get</code> and <code>set</code> indicating the
383     * month. This is a calendar-specific value. The first month of
384     * the year in the Gregorian and Julian calendars is
385     * <code>JANUARY</code> which is 0; the last depends on the number
386     * of months in a year.
387     *
388     * @see #JANUARY
389     * @see #FEBRUARY
390     * @see #MARCH
391     * @see #APRIL
392     * @see #MAY
393     * @see #JUNE
394     * @see #JULY
395     * @see #AUGUST
396     * @see #SEPTEMBER
397     * @see #OCTOBER
398     * @see #NOVEMBER
399     * @see #DECEMBER
400     * @see #UNDECIMBER
401     */
402    public static final int MONTH = 2;
403
404    /**
405     * Field number for <code>get</code> and <code>set</code> indicating the
406     * week number within the current year.  The first week of the year, as
407     * defined by <code>getFirstDayOfWeek()</code> and
408     * <code>getMinimalDaysInFirstWeek()</code>, has value 1.  Subclasses define
409     * the value of <code>WEEK_OF_YEAR</code> for days before the first week of
410     * the year.
411     *
412     * @see #getFirstDayOfWeek
413     * @see #getMinimalDaysInFirstWeek
414     */
415    public static final int WEEK_OF_YEAR = 3;
416
417    /**
418     * Field number for <code>get</code> and <code>set</code> indicating the
419     * week number within the current month.  The first week of the month, as
420     * defined by <code>getFirstDayOfWeek()</code> and
421     * <code>getMinimalDaysInFirstWeek()</code>, has value 1.  Subclasses define
422     * the value of <code>WEEK_OF_MONTH</code> for days before the first week of
423     * the month.
424     *
425     * @see #getFirstDayOfWeek
426     * @see #getMinimalDaysInFirstWeek
427     */
428    public static final int WEEK_OF_MONTH = 4;
429
430    /**
431     * Field number for <code>get</code> and <code>set</code> indicating the
432     * day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.
433     * The first day of the month has value 1.
434     *
435     * @see #DAY_OF_MONTH
436     */
437    public static final int DATE = 5;
438
439    /**
440     * Field number for <code>get</code> and <code>set</code> indicating the
441     * day of the month. This is a synonym for <code>DATE</code>.
442     * The first day of the month has value 1.
443     *
444     * @see #DATE
445     */
446    public static final int DAY_OF_MONTH = 5;
447
448    /**
449     * Field number for <code>get</code> and <code>set</code> indicating the day
450     * number within the current year.  The first day of the year has value 1.
451     */
452    public static final int DAY_OF_YEAR = 6;
453
454    /**
455     * Field number for <code>get</code> and <code>set</code> indicating the day
456     * of the week.  This field takes values <code>SUNDAY</code>,
457     * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>,
458     * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.
459     *
460     * @see #SUNDAY
461     * @see #MONDAY
462     * @see #TUESDAY
463     * @see #WEDNESDAY
464     * @see #THURSDAY
465     * @see #FRIDAY
466     * @see #SATURDAY
467     */
468    public static final int DAY_OF_WEEK = 7;
469
470    /**
471     * Field number for <code>get</code> and <code>set</code> indicating the
472     * ordinal number of the day of the week within the current month. Together
473     * with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day
474     * within a month.  Unlike <code>WEEK_OF_MONTH</code> and
475     * <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on
476     * <code>getFirstDayOfWeek()</code> or
477     * <code>getMinimalDaysInFirstWeek()</code>.  <code>DAY_OF_MONTH 1</code>
478     * through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH
479     * 1</code>; <code>8</code> through <code>14</code> correspond to
480     * <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on.
481     * <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before
482     * <code>DAY_OF_WEEK_IN_MONTH 1</code>.  Negative values count back from the
483     * end of the month, so the last Sunday of a month is specified as
484     * <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>.  Because
485     * negative values count backward they will usually be aligned differently
486     * within the month than positive values.  For example, if a month has 31
487     * days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap
488     * <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>.
489     *
490     * @see #DAY_OF_WEEK
491     * @see #WEEK_OF_MONTH
492     */
493    public static final int DAY_OF_WEEK_IN_MONTH = 8;
494
495    /**
496     * Field number for <code>get</code> and <code>set</code> indicating
497     * whether the <code>HOUR</code> is before or after noon.
498     * E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>.
499     *
500     * @see #AM
501     * @see #PM
502     * @see #HOUR
503     */
504    public static final int AM_PM = 9;
505
506    /**
507     * Field number for <code>get</code> and <code>set</code> indicating the
508     * hour of the morning or afternoon. <code>HOUR</code> is used for the
509     * 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12.
510     * E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10.
511     *
512     * @see #AM_PM
513     * @see #HOUR_OF_DAY
514     */
515    public static final int HOUR = 10;
516
517    /**
518     * Field number for <code>get</code> and <code>set</code> indicating the
519     * hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock.
520     * E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22.
521     *
522     * @see #HOUR
523     */
524    public static final int HOUR_OF_DAY = 11;
525
526    /**
527     * Field number for <code>get</code> and <code>set</code> indicating the
528     * minute within the hour.
529     * E.g., at 10:04:15.250 PM the <code>MINUTE</code> is 4.
530     */
531    public static final int MINUTE = 12;
532
533    /**
534     * Field number for <code>get</code> and <code>set</code> indicating the
535     * second within the minute.
536     * E.g., at 10:04:15.250 PM the <code>SECOND</code> is 15.
537     */
538    public static final int SECOND = 13;
539
540    /**
541     * Field number for <code>get</code> and <code>set</code> indicating the
542     * millisecond within the second.
543     * E.g., at 10:04:15.250 PM the <code>MILLISECOND</code> is 250.
544     */
545    public static final int MILLISECOND = 14;
546
547    /**
548     * Field number for <code>get</code> and <code>set</code>
549     * indicating the raw offset from GMT in milliseconds.
550     * <p>
551     * This field reflects the correct GMT offset value of the time
552     * zone of this <code>Calendar</code> if the
553     * <code>TimeZone</code> implementation subclass supports
554     * historical GMT offset changes.
555     */
556    public static final int ZONE_OFFSET = 15;
557
558    /**
559     * Field number for <code>get</code> and <code>set</code> indicating the
560     * daylight saving offset in milliseconds.
561     * <p>
562     * This field reflects the correct daylight saving offset value of
563     * the time zone of this <code>Calendar</code> if the
564     * <code>TimeZone</code> implementation subclass supports
565     * historical Daylight Saving Time schedule changes.
566     */
567    public static final int DST_OFFSET = 16;
568
569    /**
570     * The number of distinct fields recognized by <code>get</code> and <code>set</code>.
571     * Field numbers range from <code>0..FIELD_COUNT-1</code>.
572     */
573    public static final int FIELD_COUNT = 17;
574
575    /**
576     * Value of the {@link #DAY_OF_WEEK} field indicating
577     * Sunday.
578     */
579    public static final int SUNDAY = 1;
580
581    /**
582     * Value of the {@link #DAY_OF_WEEK} field indicating
583     * Monday.
584     */
585    public static final int MONDAY = 2;
586
587    /**
588     * Value of the {@link #DAY_OF_WEEK} field indicating
589     * Tuesday.
590     */
591    public static final int TUESDAY = 3;
592
593    /**
594     * Value of the {@link #DAY_OF_WEEK} field indicating
595     * Wednesday.
596     */
597    public static final int WEDNESDAY = 4;
598
599    /**
600     * Value of the {@link #DAY_OF_WEEK} field indicating
601     * Thursday.
602     */
603    public static final int THURSDAY = 5;
604
605    /**
606     * Value of the {@link #DAY_OF_WEEK} field indicating
607     * Friday.
608     */
609    public static final int FRIDAY = 6;
610
611    /**
612     * Value of the {@link #DAY_OF_WEEK} field indicating
613     * Saturday.
614     */
615    public static final int SATURDAY = 7;
616
617    /**
618     * Value of the {@link #MONTH} field indicating the
619     * first month of the year in the Gregorian and Julian calendars.
620     */
621    public static final int JANUARY = 0;
622
623    /**
624     * Value of the {@link #MONTH} field indicating the
625     * second month of the year in the Gregorian and Julian calendars.
626     */
627    public static final int FEBRUARY = 1;
628
629    /**
630     * Value of the {@link #MONTH} field indicating the
631     * third month of the year in the Gregorian and Julian calendars.
632     */
633    public static final int MARCH = 2;
634
635    /**
636     * Value of the {@link #MONTH} field indicating the
637     * fourth month of the year in the Gregorian and Julian calendars.
638     */
639    public static final int APRIL = 3;
640
641    /**
642     * Value of the {@link #MONTH} field indicating the
643     * fifth month of the year in the Gregorian and Julian calendars.
644     */
645    public static final int MAY = 4;
646
647    /**
648     * Value of the {@link #MONTH} field indicating the
649     * sixth month of the year in the Gregorian and Julian calendars.
650     */
651    public static final int JUNE = 5;
652
653    /**
654     * Value of the {@link #MONTH} field indicating the
655     * seventh month of the year in the Gregorian and Julian calendars.
656     */
657    public static final int JULY = 6;
658
659    /**
660     * Value of the {@link #MONTH} field indicating the
661     * eighth month of the year in the Gregorian and Julian calendars.
662     */
663    public static final int AUGUST = 7;
664
665    /**
666     * Value of the {@link #MONTH} field indicating the
667     * ninth month of the year in the Gregorian and Julian calendars.
668     */
669    public static final int SEPTEMBER = 8;
670
671    /**
672     * Value of the {@link #MONTH} field indicating the
673     * tenth month of the year in the Gregorian and Julian calendars.
674     */
675    public static final int OCTOBER = 9;
676
677    /**
678     * Value of the {@link #MONTH} field indicating the
679     * eleventh month of the year in the Gregorian and Julian calendars.
680     */
681    public static final int NOVEMBER = 10;
682
683    /**
684     * Value of the {@link #MONTH} field indicating the
685     * twelfth month of the year in the Gregorian and Julian calendars.
686     */
687    public static final int DECEMBER = 11;
688
689    /**
690     * Value of the {@link #MONTH} field indicating the
691     * thirteenth month of the year. Although <code>GregorianCalendar</code>
692     * does not use this value, lunar calendars do.
693     */
694    public static final int UNDECIMBER = 12;
695
696    /**
697     * Value of the {@link #AM_PM} field indicating the
698     * period of the day from midnight to just before noon.
699     */
700    public static final int AM = 0;
701
702    /**
703     * Value of the {@link #AM_PM} field indicating the
704     * period of the day from noon to just before midnight.
705     */
706    public static final int PM = 1;
707
708    /**
709     * A style specifier for {@link #getDisplayNames(int, int, Locale)
710     * getDisplayNames} indicating names in all styles, such as
711     * "January" and "Jan".
712     *
713     * @see #SHORT_FORMAT
714     * @see #LONG_FORMAT
715     * @see #SHORT_STANDALONE
716     * @see #LONG_STANDALONE
717     * @see #SHORT
718     * @see #LONG
719     * @since 1.6
720     */
721    public static final int ALL_STYLES = 0;
722
723    static final int STANDALONE_MASK = 0x8000;
724
725    /**
726     * A style specifier for {@link #getDisplayName(int, int, Locale)
727     * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
728     * getDisplayNames} equivalent to {@link #SHORT_FORMAT}.
729     *
730     * @see #SHORT_STANDALONE
731     * @see #LONG
732     * @since 1.6
733     */
734    public static final int SHORT = 1;
735
736    /**
737     * A style specifier for {@link #getDisplayName(int, int, Locale)
738     * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
739     * getDisplayNames} equivalent to {@link #LONG_FORMAT}.
740     *
741     * @see #LONG_STANDALONE
742     * @see #SHORT
743     * @since 1.6
744     */
745    public static final int LONG = 2;
746
747    /**
748     * A style specifier for {@link #getDisplayName(int, int, Locale)
749     * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
750     * getDisplayNames} indicating a narrow name used for format. Narrow names
751     * are typically single character strings, such as "M" for Monday.
752     *
753     * @see #NARROW_STANDALONE
754     * @see #SHORT_FORMAT
755     * @see #LONG_FORMAT
756     * @since 1.8
757     */
758    public static final int NARROW_FORMAT = 4;
759
760    /**
761     * A style specifier for {@link #getDisplayName(int, int, Locale)
762     * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
763     * getDisplayNames} indicating a narrow name independently. Narrow names
764     * are typically single character strings, such as "M" for Monday.
765     *
766     * @see #NARROW_FORMAT
767     * @see #SHORT_STANDALONE
768     * @see #LONG_STANDALONE
769     * @since 1.8
770     */
771    public static final int NARROW_STANDALONE = NARROW_FORMAT | STANDALONE_MASK;
772
773    /**
774     * A style specifier for {@link #getDisplayName(int, int, Locale)
775     * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
776     * getDisplayNames} indicating a short name used for format.
777     *
778     * @see #SHORT_STANDALONE
779     * @see #LONG_FORMAT
780     * @see #LONG_STANDALONE
781     * @since 1.8
782     */
783    public static final int SHORT_FORMAT = 1;
784
785    /**
786     * A style specifier for {@link #getDisplayName(int, int, Locale)
787     * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
788     * getDisplayNames} indicating a long name used for format.
789     *
790     * @see #LONG_STANDALONE
791     * @see #SHORT_FORMAT
792     * @see #SHORT_STANDALONE
793     * @since 1.8
794     */
795    public static final int LONG_FORMAT = 2;
796
797    /**
798     * A style specifier for {@link #getDisplayName(int, int, Locale)
799     * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
800     * getDisplayNames} indicating a short name used independently,
801     * such as a month abbreviation as calendar headers.
802     *
803     * @see #SHORT_FORMAT
804     * @see #LONG_FORMAT
805     * @see #LONG_STANDALONE
806     * @since 1.8
807     */
808    public static final int SHORT_STANDALONE = SHORT | STANDALONE_MASK;
809
810    /**
811     * A style specifier for {@link #getDisplayName(int, int, Locale)
812     * getDisplayName} and {@link #getDisplayNames(int, int, Locale)
813     * getDisplayNames} indicating a long name used independently,
814     * such as a month name as calendar headers.
815     *
816     * @see #LONG_FORMAT
817     * @see #SHORT_FORMAT
818     * @see #SHORT_STANDALONE
819     * @since 1.8
820     */
821    public static final int LONG_STANDALONE = LONG | STANDALONE_MASK;
822
823    // Internal notes:
824    // Calendar contains two kinds of time representations: current "time" in
825    // milliseconds, and a set of calendar "fields" representing the current time.
826    // The two representations are usually in sync, but can get out of sync
827    // as follows.
828    // 1. Initially, no fields are set, and the time is invalid.
829    // 2. If the time is set, all fields are computed and in sync.
830    // 3. If a single field is set, the time is invalid.
831    // Recomputation of the time and fields happens when the object needs
832    // to return a result to the user, or use a result for a computation.
833
834    /**
835     * The calendar field values for the currently set time for this calendar.
836     * This is an array of <code>FIELD_COUNT</code> integers, with index values
837     * <code>ERA</code> through <code>DST_OFFSET</code>.
838     * @serial
839     */
840    @SuppressWarnings("ProtectedField")
841    protected int           fields[];
842
843    /**
844     * The flags which tell if a specified calendar field for the calendar is set.
845     * A new object has no fields set.  After the first call to a method
846     * which generates the fields, they all remain set after that.
847     * This is an array of <code>FIELD_COUNT</code> booleans, with index values
848     * <code>ERA</code> through <code>DST_OFFSET</code>.
849     * @serial
850     */
851    @SuppressWarnings("ProtectedField")
852    protected boolean       isSet[];
853
854    /**
855     * Pseudo-time-stamps which specify when each field was set. There
856     * are two special values, UNSET and COMPUTED. Values from
857     * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values.
858     */
859    private transient int   stamp[];
860
861    /**
862     * The currently set time for this calendar, expressed in milliseconds after
863     * January 1, 1970, 0:00:00 GMT.
864     * @see #isTimeSet
865     * @serial
866     */
867    @SuppressWarnings("ProtectedField")
868    protected long          time;
869
870    /**
871     * True if then the value of <code>time</code> is valid.
872     * The time is made invalid by a change to an item of <code>field[]</code>.
873     * @see #time
874     * @serial
875     */
876    @SuppressWarnings("ProtectedField")
877    protected boolean       isTimeSet;
878
879    /**
880     * True if <code>fields[]</code> are in sync with the currently set time.
881     * If false, then the next attempt to get the value of a field will
882     * force a recomputation of all fields from the current value of
883     * <code>time</code>.
884     * @serial
885     */
886    @SuppressWarnings("ProtectedField")
887    protected boolean       areFieldsSet;
888
889    /**
890     * True if all fields have been set.
891     * @serial
892     */
893    transient boolean       areAllFieldsSet;
894
895    /**
896     * <code>True</code> if this calendar allows out-of-range field values during computation
897     * of <code>time</code> from <code>fields[]</code>.
898     * @see #setLenient
899     * @see #isLenient
900     * @serial
901     */
902    private boolean         lenient = true;
903
904    /**
905     * The <code>TimeZone</code> used by this calendar. <code>Calendar</code>
906     * uses the time zone data to translate between locale and GMT time.
907     * @serial
908     */
909    private TimeZone        zone;
910
911    /**
912     * <code>True</code> if zone references to a shared TimeZone object.
913     */
914    private transient boolean sharedZone = false;
915
916    /**
917     * The first day of the week, with possible values <code>SUNDAY</code>,
918     * <code>MONDAY</code>, etc.  This is a locale-dependent value.
919     * @serial
920     */
921    private int             firstDayOfWeek;
922
923    /**
924     * The number of days required for the first week in a month or year,
925     * with possible values from 1 to 7.  This is a locale-dependent value.
926     * @serial
927     */
928    private int             minimalDaysInFirstWeek;
929
930    /**
931     * Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek
932     * of a Locale.
933     */
934    private static final ConcurrentMap<Locale, int[]> cachedLocaleData
935        = new ConcurrentHashMap<>(3);
936
937    // Special values of stamp[]
938    /**
939     * The corresponding fields[] has no value.
940     */
941    private static final int        UNSET = 0;
942
943    /**
944     * The value of the corresponding fields[] has been calculated internally.
945     */
946    private static final int        COMPUTED = 1;
947
948    /**
949     * The value of the corresponding fields[] has been set externally. Stamp
950     * values which are greater than 1 represents the (pseudo) time when the
951     * corresponding fields[] value was set.
952     */
953    private static final int        MINIMUM_USER_STAMP = 2;
954
955    /**
956     * The mask value that represents all of the fields.
957     */
958    static final int ALL_FIELDS = (1 << FIELD_COUNT) - 1;
959
960    /**
961     * The next available value for <code>stamp[]</code>, an internal array.
962     * This actually should not be written out to the stream, and will probably
963     * be removed from the stream in the near future.  In the meantime,
964     * a value of <code>MINIMUM_USER_STAMP</code> should be used.
965     * @serial
966     */
967    private int             nextStamp = MINIMUM_USER_STAMP;
968
969    // the internal serial version which says which version was written
970    // - 0 (default) for version up to JDK 1.1.5
971    // - 1 for version from JDK 1.1.6, which writes a correct 'time' value
972    //     as well as compatible values for other fields.  This is a
973    //     transitional format.
974    // - 2 (not implemented yet) a future version, in which fields[],
975    //     areFieldsSet, and isTimeSet become transient, and isSet[] is
976    //     removed. In JDK 1.1.6 we write a format compatible with version 2.
977    static final int        currentSerialVersion = 1;
978
979    /**
980     * The version of the serialized data on the stream.  Possible values:
981     * <dl>
982     * <dt><b>0</b> or not present on stream</dt>
983     * <dd>
984     * JDK 1.1.5 or earlier.
985     * </dd>
986     * <dt><b>1</b></dt>
987     * <dd>
988     * JDK 1.1.6 or later.  Writes a correct 'time' value
989     * as well as compatible values for other fields.  This is a
990     * transitional format.
991     * </dd>
992     * </dl>
993     * When streaming out this class, the most recent format
994     * and the highest allowable <code>serialVersionOnStream</code>
995     * is written.
996     * @serial
997     * @since 1.1.6
998     */
999    private int             serialVersionOnStream = currentSerialVersion;
1000
1001    // Proclaim serialization compatibility with JDK 1.1
1002    static final long       serialVersionUID = -1807547505821590642L;
1003
1004    // Mask values for calendar fields
1005    @SuppressWarnings("PointlessBitwiseExpression")
1006    static final int ERA_MASK           = (1 << ERA);
1007    static final int YEAR_MASK          = (1 << YEAR);
1008    static final int MONTH_MASK         = (1 << MONTH);
1009    static final int WEEK_OF_YEAR_MASK  = (1 << WEEK_OF_YEAR);
1010    static final int WEEK_OF_MONTH_MASK = (1 << WEEK_OF_MONTH);
1011    static final int DAY_OF_MONTH_MASK  = (1 << DAY_OF_MONTH);
1012    static final int DATE_MASK          = DAY_OF_MONTH_MASK;
1013    static final int DAY_OF_YEAR_MASK   = (1 << DAY_OF_YEAR);
1014    static final int DAY_OF_WEEK_MASK   = (1 << DAY_OF_WEEK);
1015    static final int DAY_OF_WEEK_IN_MONTH_MASK  = (1 << DAY_OF_WEEK_IN_MONTH);
1016    static final int AM_PM_MASK         = (1 << AM_PM);
1017    static final int HOUR_MASK          = (1 << HOUR);
1018    static final int HOUR_OF_DAY_MASK   = (1 << HOUR_OF_DAY);
1019    static final int MINUTE_MASK        = (1 << MINUTE);
1020    static final int SECOND_MASK        = (1 << SECOND);
1021    static final int MILLISECOND_MASK   = (1 << MILLISECOND);
1022    static final int ZONE_OFFSET_MASK   = (1 << ZONE_OFFSET);
1023    static final int DST_OFFSET_MASK    = (1 << DST_OFFSET);
1024
1025    /**
1026     * {@code Calendar.Builder} is used for creating a {@code Calendar} from
1027     * various date-time parameters.
1028     *
1029     * <p>There are two ways to set a {@code Calendar} to a date-time value. One
1030     * is to set the instant parameter to a millisecond offset from the <a
1031     * href="Calendar.html#Epoch">Epoch</a>. The other is to set individual
1032     * field parameters, such as {@link Calendar#YEAR YEAR}, to their desired
1033     * values. These two ways can't be mixed. Trying to set both the instant and
1034     * individual fields will cause an {@link IllegalStateException} to be
1035     * thrown. However, it is permitted to override previous values of the
1036     * instant or field parameters.
1037     *
1038     * <p>If no enough field parameters are given for determining date and/or
1039     * time, calendar specific default values are used when building a
1040     * {@code Calendar}. For example, if the {@link Calendar#YEAR YEAR} value
1041     * isn't given for the Gregorian calendar, 1970 will be used. If there are
1042     * any conflicts among field parameters, the <a
1043     * href="Calendar.html#resolution"> resolution rules</a> are applied.
1044     * Therefore, the order of field setting matters.
1045     *
1046     * <p>In addition to the date-time parameters,
1047     * the {@linkplain #setLocale(Locale) locale},
1048     * {@linkplain #setTimeZone(TimeZone) time zone},
1049     * {@linkplain #setWeekDefinition(int, int) week definition}, and
1050     * {@linkplain #setLenient(boolean) leniency mode} parameters can be set.
1051     *
1052     * <p><b>Examples</b>
1053     * <p>The following are sample usages. Sample code assumes that the
1054     * {@code Calendar} constants are statically imported.
1055     *
1056     * <p>The following code produces a {@code Calendar} with date 2012-12-31
1057     * (Gregorian) because Monday is the first day of a week with the <a
1058     * href="GregorianCalendar.html#iso8601_compatible_setting"> ISO 8601
1059     * compatible week parameters</a>.
1060     * <pre>
1061     *   Calendar cal = new Calendar.Builder().setCalendarType("iso8601")
1062     *                        .setWeekDate(2013, 1, MONDAY).build();</pre>
1063     * <p>The following code produces a Japanese {@code Calendar} with date
1064     * 1989-01-08 (Gregorian), assuming that the default {@link Calendar#ERA ERA}
1065     * is <em>Heisei</em> that started on that day.
1066     * <pre>
1067     *   Calendar cal = new Calendar.Builder().setCalendarType("japanese")
1068     *                        .setFields(YEAR, 1, DAY_OF_YEAR, 1).build();</pre>
1069     *
1070     * @since 1.8
1071     * @see Calendar#getInstance(TimeZone, Locale)
1072     * @see Calendar#fields
1073     */
1074    public static class Builder {
1075        private static final int NFIELDS = FIELD_COUNT + 1; // +1 for WEEK_YEAR
1076        private static final int WEEK_YEAR = FIELD_COUNT;
1077
1078        private long instant;
1079        // Calendar.stamp[] (lower half) and Calendar.fields[] (upper half) combined
1080        private int[] fields;
1081        // Pseudo timestamp starting from MINIMUM_USER_STAMP.
1082        // (COMPUTED is used to indicate that the instant has been set.)
1083        private int nextStamp;
1084        // maxFieldIndex keeps the max index of fields which have been set.
1085        // (WEEK_YEAR is never included.)
1086        private int maxFieldIndex;
1087        private String type;
1088        private TimeZone zone;
1089        private boolean lenient = true;
1090        private Locale locale;
1091        private int firstDayOfWeek, minimalDaysInFirstWeek;
1092
1093        /**
1094         * Constructs a {@code Calendar.Builder}.
1095         */
1096        public Builder() {
1097        }
1098
1099        /**
1100         * Sets the instant parameter to the given {@code instant} value that is
1101         * a millisecond offset from <a href="Calendar.html#Epoch">the
1102         * Epoch</a>.
1103         *
1104         * @param instant a millisecond offset from the Epoch
1105         * @return this {@code Calendar.Builder}
1106         * @throws IllegalStateException if any of the field parameters have
1107         *                               already been set
1108         * @see Calendar#setTime(Date)
1109         * @see Calendar#setTimeInMillis(long)
1110         * @see Calendar#time
1111         */
1112        public Builder setInstant(long instant) {
1113            if (fields != null) {
1114                throw new IllegalStateException();
1115            }
1116            this.instant = instant;
1117            nextStamp = COMPUTED;
1118            return this;
1119        }
1120
1121        /**
1122         * Sets the instant parameter to the {@code instant} value given by a
1123         * {@link Date}. This method is equivalent to a call to
1124         * {@link #setInstant(long) setInstant(instant.getTime())}.
1125         *
1126         * @param instant a {@code Date} representing a millisecond offset from
1127         *                the Epoch
1128         * @return this {@code Calendar.Builder}
1129         * @throws NullPointerException  if {@code instant} is {@code null}
1130         * @throws IllegalStateException if any of the field parameters have
1131         *                               already been set
1132         * @see Calendar#setTime(Date)
1133         * @see Calendar#setTimeInMillis(long)
1134         * @see Calendar#time
1135         */
1136        public Builder setInstant(Date instant) {
1137            return setInstant(instant.getTime()); // NPE if instant == null
1138        }
1139
1140        /**
1141         * Sets the {@code field} parameter to the given {@code value}.
1142         * {@code field} is an index to the {@link Calendar#fields}, such as
1143         * {@link Calendar#DAY_OF_MONTH DAY_OF_MONTH}. Field value validation is
1144         * not performed in this method. Any out of range values are either
1145         * normalized in lenient mode or detected as an invalid value in
1146         * non-lenient mode when building a {@code Calendar}.
1147         *
1148         * @param field an index to the {@code Calendar} fields
1149         * @param value the field value
1150         * @return this {@code Calendar.Builder}
1151         * @throws IllegalArgumentException if {@code field} is invalid
1152         * @throws IllegalStateException if the instant value has already been set,
1153         *                      or if fields have been set too many
1154         *                      (approximately {@link Integer#MAX_VALUE}) times.
1155         * @see Calendar#set(int, int)
1156         */
1157        public Builder set(int field, int value) {
1158            // Note: WEEK_YEAR can't be set with this method.
1159            if (field < 0 || field >= FIELD_COUNT) {
1160                throw new IllegalArgumentException("field is invalid");
1161            }
1162            if (isInstantSet()) {
1163                throw new IllegalStateException("instant has been set");
1164            }
1165            allocateFields();
1166            internalSet(field, value);
1167            return this;
1168        }
1169
1170        /**
1171         * Sets field parameters to their values given by
1172         * {@code fieldValuePairs} that are pairs of a field and its value.
1173         * For example,
1174         * <pre>
1175         *   setFields(Calendar.YEAR, 2013,
1176         *             Calendar.MONTH, Calendar.DECEMBER,
1177         *             Calendar.DAY_OF_MONTH, 23);</pre>
1178         * is equivalent to the sequence of the following
1179         * {@link #set(int, int) set} calls:
1180         * <pre>
1181         *   set(Calendar.YEAR, 2013)
1182         *   .set(Calendar.MONTH, Calendar.DECEMBER)
1183         *   .set(Calendar.DAY_OF_MONTH, 23);</pre>
1184         *
1185         * @param fieldValuePairs field-value pairs
1186         * @return this {@code Calendar.Builder}
1187         * @throws NullPointerException if {@code fieldValuePairs} is {@code null}
1188         * @throws IllegalArgumentException if any of fields are invalid,
1189         *             or if {@code fieldValuePairs.length} is an odd number.
1190         * @throws IllegalStateException    if the instant value has been set,
1191         *             or if fields have been set too many (approximately
1192         *             {@link Integer#MAX_VALUE}) times.
1193         */
1194        public Builder setFields(int... fieldValuePairs) {
1195            int len = fieldValuePairs.length;
1196            if ((len % 2) != 0) {
1197                throw new IllegalArgumentException();
1198            }
1199            if (isInstantSet()) {
1200                throw new IllegalStateException("instant has been set");
1201            }
1202            if ((nextStamp + len / 2) < 0) {
1203                throw new IllegalStateException("stamp counter overflow");
1204            }
1205            allocateFields();
1206            for (int i = 0; i < len; ) {
1207                int field = fieldValuePairs[i++];
1208                // Note: WEEK_YEAR can't be set with this method.
1209                if (field < 0 || field >= FIELD_COUNT) {
1210                    throw new IllegalArgumentException("field is invalid");
1211                }
1212                internalSet(field, fieldValuePairs[i++]);
1213            }
1214            return this;
1215        }
1216
1217        /**
1218         * Sets the date field parameters to the values given by {@code year},
1219         * {@code month}, and {@code dayOfMonth}. This method is equivalent to
1220         * a call to:
1221         * <pre>
1222         *   setFields(Calendar.YEAR, year,
1223         *             Calendar.MONTH, month,
1224         *             Calendar.DAY_OF_MONTH, dayOfMonth);</pre>
1225         *
1226         * @param year       the {@link Calendar#YEAR YEAR} value
1227         * @param month      the {@link Calendar#MONTH MONTH} value
1228         *                   (the month numbering is <em>0-based</em>).
1229         * @param dayOfMonth the {@link Calendar#DAY_OF_MONTH DAY_OF_MONTH} value
1230         * @return this {@code Calendar.Builder}
1231         */
1232        public Builder setDate(int year, int month, int dayOfMonth) {
1233            return setFields(YEAR, year, MONTH, month, DAY_OF_MONTH, dayOfMonth);
1234        }
1235
1236        /**
1237         * Sets the time of day field parameters to the values given by
1238         * {@code hourOfDay}, {@code minute}, and {@code second}. This method is
1239         * equivalent to a call to:
1240         * <pre>
1241         *   setTimeOfDay(hourOfDay, minute, second, 0);</pre>
1242         *
1243         * @param hourOfDay the {@link Calendar#HOUR_OF_DAY HOUR_OF_DAY} value
1244         *                  (24-hour clock)
1245         * @param minute    the {@link Calendar#MINUTE MINUTE} value
1246         * @param second    the {@link Calendar#SECOND SECOND} value
1247         * @return this {@code Calendar.Builder}
1248         */
1249        public Builder setTimeOfDay(int hourOfDay, int minute, int second) {
1250            return setTimeOfDay(hourOfDay, minute, second, 0);
1251        }
1252
1253        /**
1254         * Sets the time of day field parameters to the values given by
1255         * {@code hourOfDay}, {@code minute}, {@code second}, and
1256         * {@code millis}. This method is equivalent to a call to:
1257         * <pre>
1258         *   setFields(Calendar.HOUR_OF_DAY, hourOfDay,
1259         *             Calendar.MINUTE, minute,
1260         *             Calendar.SECOND, second,
1261         *             Calendar.MILLISECOND, millis);</pre>
1262         *
1263         * @param hourOfDay the {@link Calendar#HOUR_OF_DAY HOUR_OF_DAY} value
1264         *                  (24-hour clock)
1265         * @param minute    the {@link Calendar#MINUTE MINUTE} value
1266         * @param second    the {@link Calendar#SECOND SECOND} value
1267         * @param millis    the {@link Calendar#MILLISECOND MILLISECOND} value
1268         * @return this {@code Calendar.Builder}
1269         */
1270        public Builder setTimeOfDay(int hourOfDay, int minute, int second, int millis) {
1271            return setFields(HOUR_OF_DAY, hourOfDay, MINUTE, minute,
1272                             SECOND, second, MILLISECOND, millis);
1273        }
1274
1275        /**
1276         * Sets the week-based date parameters to the values with the given
1277         * date specifiers - week year, week of year, and day of week.
1278         *
1279         * <p>If the specified calendar doesn't support week dates, the
1280         * {@link #build() build} method will throw an {@link IllegalArgumentException}.
1281         *
1282         * @param weekYear   the week year
1283         * @param weekOfYear the week number based on {@code weekYear}
1284         * @param dayOfWeek  the day of week value: one of the constants
1285         *     for the {@link Calendar#DAY_OF_WEEK DAY_OF_WEEK} field:
1286         *     {@link Calendar#SUNDAY SUNDAY}, ..., {@link Calendar#SATURDAY SATURDAY}.
1287         * @return this {@code Calendar.Builder}
1288         * @see Calendar#setWeekDate(int, int, int)
1289         * @see Calendar#isWeekDateSupported()
1290         */
1291        public Builder setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
1292            allocateFields();
1293            internalSet(WEEK_YEAR, weekYear);
1294            internalSet(WEEK_OF_YEAR, weekOfYear);
1295            internalSet(DAY_OF_WEEK, dayOfWeek);
1296            return this;
1297        }
1298
1299        /**
1300         * Sets the time zone parameter to the given {@code zone}. If no time
1301         * zone parameter is given to this {@code Calendar.Builder}, the
1302         * {@linkplain TimeZone#getDefault() default
1303         * <code>TimeZone</code>} will be used in the {@link #build() build}
1304         * method.
1305         *
1306         * @param zone the {@link TimeZone}
1307         * @return this {@code Calendar.Builder}
1308         * @throws NullPointerException if {@code zone} is {@code null}
1309         * @see Calendar#setTimeZone(TimeZone)
1310         */
1311        public Builder setTimeZone(TimeZone zone) {
1312            if (zone == null) {
1313                throw new NullPointerException();
1314            }
1315            this.zone = zone;
1316            return this;
1317        }
1318
1319        /**
1320         * Sets the lenient mode parameter to the value given by {@code lenient}.
1321         * If no lenient parameter is given to this {@code Calendar.Builder},
1322         * lenient mode will be used in the {@link #build() build} method.
1323         *
1324         * @param lenient {@code true} for lenient mode;
1325         *                {@code false} for non-lenient mode
1326         * @return this {@code Calendar.Builder}
1327         * @see Calendar#setLenient(boolean)
1328         */
1329        public Builder setLenient(boolean lenient) {
1330            this.lenient = lenient;
1331            return this;
1332        }
1333
1334        /**
1335         * Sets the calendar type parameter to the given {@code type}. The
1336         * calendar type given by this method has precedence over any explicit
1337         * or implicit calendar type given by the
1338         * {@linkplain #setLocale(Locale) locale}.
1339         *
1340         * <p>In addition to the available calendar types returned by the
1341         * {@link Calendar#getAvailableCalendarTypes() Calendar.getAvailableCalendarTypes}
1342         * method, {@code "gregorian"} and {@code "iso8601"} as aliases of
1343         * {@code "gregory"} can be used with this method.
1344         *
1345         * @param type the calendar type
1346         * @return this {@code Calendar.Builder}
1347         * @throws NullPointerException if {@code type} is {@code null}
1348         * @throws IllegalArgumentException if {@code type} is unknown
1349         * @throws IllegalStateException if another calendar type has already been set
1350         * @see Calendar#getCalendarType()
1351         * @see Calendar#getAvailableCalendarTypes()
1352         */
1353        public Builder setCalendarType(String type) {
1354            if (type.equals("gregorian")) { // NPE if type == null
1355                type = "gregory";
1356            }
1357            if (!Calendar.getAvailableCalendarTypes().contains(type)
1358                    && !type.equals("iso8601")) {
1359                throw new IllegalArgumentException("unknown calendar type: " + type);
1360            }
1361            if (this.type == null) {
1362                this.type = type;
1363            } else {
1364                if (!this.type.equals(type)) {
1365                    throw new IllegalStateException("calendar type override");
1366                }
1367            }
1368            return this;
1369        }
1370
1371        /**
1372         * Sets the locale parameter to the given {@code locale}. If no locale
1373         * is given to this {@code Calendar.Builder}, the {@linkplain
1374         * Locale#getDefault(Locale.Category) default <code>Locale</code>}
1375         * for {@link Locale.Category#FORMAT} will be used.
1376         *
1377         * <p>If no calendar type is explicitly given by a call to the
1378         * {@link #setCalendarType(String) setCalendarType} method,
1379         * the {@code Locale} value is used to determine what type of
1380         * {@code Calendar} to be built.
1381         *
1382         * <p>If no week definition parameters are explicitly given by a call to
1383         * the {@link #setWeekDefinition(int,int) setWeekDefinition} method, the
1384         * {@code Locale}'s default values are used.
1385         *
1386         * @param locale the {@link Locale}
1387         * @throws NullPointerException if {@code locale} is {@code null}
1388         * @return this {@code Calendar.Builder}
1389         * @see Calendar#getInstance(Locale)
1390         */
1391        public Builder setLocale(Locale locale) {
1392            if (locale == null) {
1393                throw new NullPointerException();
1394            }
1395            this.locale = locale;
1396            return this;
1397        }
1398
1399        /**
1400         * Sets the week definition parameters to the values given by
1401         * {@code firstDayOfWeek} and {@code minimalDaysInFirstWeek} that are
1402         * used to determine the <a href="Calendar.html#First_Week">first
1403         * week</a> of a year. The parameters given by this method have
1404         * precedence over the default values given by the
1405         * {@linkplain #setLocale(Locale) locale}.
1406         *
1407         * @param firstDayOfWeek the first day of a week; one of
1408         *                       {@link Calendar#SUNDAY} to {@link Calendar#SATURDAY}
1409         * @param minimalDaysInFirstWeek the minimal number of days in the first
1410         *                               week (1..7)
1411         * @return this {@code Calendar.Builder}
1412         * @throws IllegalArgumentException if {@code firstDayOfWeek} or
1413         *                                  {@code minimalDaysInFirstWeek} is invalid
1414         * @see Calendar#getFirstDayOfWeek()
1415         * @see Calendar#getMinimalDaysInFirstWeek()
1416         */
1417        public Builder setWeekDefinition(int firstDayOfWeek, int minimalDaysInFirstWeek) {
1418            if (!isValidWeekParameter(firstDayOfWeek)
1419                    || !isValidWeekParameter(minimalDaysInFirstWeek)) {
1420                throw new IllegalArgumentException();
1421            }
1422            this.firstDayOfWeek = firstDayOfWeek;
1423            this.minimalDaysInFirstWeek = minimalDaysInFirstWeek;
1424            return this;
1425        }
1426
1427        /**
1428         * Returns a {@code Calendar} built from the parameters set by the
1429         * setter methods. The calendar type given by the {@link #setCalendarType(String)
1430         * setCalendarType} method or the {@linkplain #setLocale(Locale) locale} is
1431         * used to determine what {@code Calendar} to be created. If no explicit
1432         * calendar type is given, the locale's default calendar is created.
1433         *
1434         * <p>If the calendar type is {@code "iso8601"}, the
1435         * {@linkplain GregorianCalendar#setGregorianChange(Date) Gregorian change date}
1436         * of a {@link GregorianCalendar} is set to {@code Date(Long.MIN_VALUE)}
1437         * to be the <em>proleptic</em> Gregorian calendar. Its week definition
1438         * parameters are also set to be <a
1439         * href="GregorianCalendar.html#iso8601_compatible_setting">compatible
1440         * with the ISO 8601 standard</a>. Note that the
1441         * {@link GregorianCalendar#getCalendarType() getCalendarType} method of
1442         * a {@code GregorianCalendar} created with {@code "iso8601"} returns
1443         * {@code "gregory"}.
1444         *
1445         * <p>The default values are used for locale and time zone if these
1446         * parameters haven't been given explicitly.
1447         *
1448         * <p>Any out of range field values are either normalized in lenient
1449         * mode or detected as an invalid value in non-lenient mode.
1450         *
1451         * @return a {@code Calendar} built with parameters of this {@code
1452         *         Calendar.Builder}
1453         * @throws IllegalArgumentException if the calendar type is unknown, or
1454         *             if any invalid field values are given in non-lenient mode, or
1455         *             if a week date is given for the calendar type that doesn't
1456         *             support week dates.
1457         * @see Calendar#getInstance(TimeZone, Locale)
1458         * @see Locale#getDefault(Locale.Category)
1459         * @see TimeZone#getDefault()
1460         */
1461        public Calendar build() {
1462            if (locale == null) {
1463                locale = Locale.getDefault();
1464            }
1465            if (zone == null) {
1466                zone = TimeZone.getDefault();
1467            }
1468            Calendar cal;
1469            if (type == null) {
1470                type = locale.getUnicodeLocaleType("ca");
1471            }
1472            if (type == null) {
1473                if (locale.getCountry() == "TH"
1474                    && locale.getLanguage() == "th") {
1475                    type = "buddhist";
1476                } else {
1477                    type = "gregory";
1478                }
1479            }
1480            switch (type) {
1481            case "gregory":
1482                cal = new GregorianCalendar(zone, locale, true);
1483                break;
1484            case "iso8601":
1485                GregorianCalendar gcal = new GregorianCalendar(zone, locale, true);
1486                // make gcal a proleptic Gregorian
1487                gcal.setGregorianChange(new Date(Long.MIN_VALUE));
1488                // and week definition to be compatible with ISO 8601
1489                setWeekDefinition(MONDAY, 4);
1490                cal = gcal;
1491                break;
1492            case "buddhist":
1493                cal = new BuddhistCalendar(zone, locale);
1494                cal.clear();
1495                break;
1496            case "japanese":
1497                cal = new JapaneseImperialCalendar(zone, locale, true);
1498                break;
1499            default:
1500                throw new IllegalArgumentException("unknown calendar type: " + type);
1501            }
1502            cal.setLenient(lenient);
1503            if (firstDayOfWeek != 0) {
1504                cal.setFirstDayOfWeek(firstDayOfWeek);
1505                cal.setMinimalDaysInFirstWeek(minimalDaysInFirstWeek);
1506            }
1507            if (isInstantSet()) {
1508                cal.setTimeInMillis(instant);
1509                cal.complete();
1510                return cal;
1511            }
1512
1513            if (fields != null) {
1514                boolean weekDate = isSet(WEEK_YEAR)
1515                                       && fields[WEEK_YEAR] > fields[YEAR];
1516                if (weekDate && !cal.isWeekDateSupported()) {
1517                    throw new IllegalArgumentException("week date is unsupported by " + type);
1518                }
1519
1520                // Set the fields from the min stamp to the max stamp so that
1521                // the fields resolution works in the Calendar.
1522                for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {
1523                    for (int index = 0; index <= maxFieldIndex; index++) {
1524                        if (fields[index] == stamp) {
1525                            cal.set(index, fields[NFIELDS + index]);
1526                            break;
1527                        }
1528                    }
1529                }
1530
1531                if (weekDate) {
1532                    int weekOfYear = isSet(WEEK_OF_YEAR) ? fields[NFIELDS + WEEK_OF_YEAR] : 1;
1533                    int dayOfWeek = isSet(DAY_OF_WEEK)
1534                                    ? fields[NFIELDS + DAY_OF_WEEK] : cal.getFirstDayOfWeek();
1535                    cal.setWeekDate(fields[NFIELDS + WEEK_YEAR], weekOfYear, dayOfWeek);
1536                }
1537                cal.complete();
1538            }
1539
1540            return cal;
1541        }
1542
1543        private void allocateFields() {
1544            if (fields == null) {
1545                fields = new int[NFIELDS * 2];
1546                nextStamp = MINIMUM_USER_STAMP;
1547                maxFieldIndex = -1;
1548            }
1549        }
1550
1551        private void internalSet(int field, int value) {
1552            fields[field] = nextStamp++;
1553            if (nextStamp < 0) {
1554                throw new IllegalStateException("stamp counter overflow");
1555            }
1556            fields[NFIELDS + field] = value;
1557            if (field > maxFieldIndex && field < WEEK_YEAR) {
1558                maxFieldIndex = field;
1559            }
1560        }
1561
1562        private boolean isInstantSet() {
1563            return nextStamp == COMPUTED;
1564        }
1565
1566        private boolean isSet(int index) {
1567            return fields != null && fields[index] > UNSET;
1568        }
1569
1570        private boolean isValidWeekParameter(int value) {
1571            return value > 0 && value <= 7;
1572        }
1573    }
1574
1575    /**
1576     * Constructs a Calendar with the default time zone
1577     * and the default {@link java.util.Locale.Category#FORMAT FORMAT}
1578     * locale.
1579     * @see     TimeZone#getDefault
1580     */
1581    protected Calendar()
1582    {
1583        this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
1584        sharedZone = true;
1585    }
1586
1587    /**
1588     * Constructs a calendar with the specified time zone and locale.
1589     *
1590     * @param zone the time zone to use
1591     * @param aLocale the locale for the week data
1592     */
1593    protected Calendar(TimeZone zone, Locale aLocale)
1594    {
1595        fields = new int[FIELD_COUNT];
1596        isSet = new boolean[FIELD_COUNT];
1597        stamp = new int[FIELD_COUNT];
1598
1599        this.zone = zone;
1600        setWeekCountData(aLocale);
1601    }
1602
1603    /**
1604     * Gets a calendar using the default time zone and locale. The
1605     * <code>Calendar</code> returned is based on the current time
1606     * in the default time zone with the default
1607     * {@link Locale.Category#FORMAT FORMAT} locale.
1608     *
1609     * @return a Calendar.
1610     */
1611    public static Calendar getInstance()
1612    {
1613        return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
1614    }
1615
1616    /**
1617     * Gets a calendar using the specified time zone and default locale.
1618     * The <code>Calendar</code> returned is based on the current time
1619     * in the given time zone with the default
1620     * {@link Locale.Category#FORMAT FORMAT} locale.
1621     *
1622     * @param zone the time zone to use
1623     * @return a Calendar.
1624     */
1625    public static Calendar getInstance(TimeZone zone)
1626    {
1627        return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT));
1628    }
1629
1630    /**
1631     * Gets a calendar using the default time zone and specified locale.
1632     * The <code>Calendar</code> returned is based on the current time
1633     * in the default time zone with the given locale.
1634     *
1635     * @param aLocale the locale for the week data
1636     * @return a Calendar.
1637     */
1638    public static Calendar getInstance(Locale aLocale)
1639    {
1640        return createCalendar(TimeZone.getDefault(), aLocale);
1641    }
1642
1643    /**
1644     * Gets a calendar with the specified time zone and locale.
1645     * The <code>Calendar</code> returned is based on the current time
1646     * in the given time zone with the given locale.
1647     *
1648     * @param zone the time zone to use
1649     * @param aLocale the locale for the week data
1650     * @return a Calendar.
1651     */
1652    public static Calendar getInstance(TimeZone zone,
1653                                       Locale aLocale)
1654    {
1655        return createCalendar(zone, aLocale);
1656    }
1657
1658    private static Calendar createCalendar(TimeZone zone,
1659                                           Locale aLocale)
1660    {
1661        CalendarProvider provider =
1662            LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale)
1663                                 .getCalendarProvider();
1664        if (provider != null) {
1665            try {
1666                return provider.getInstance(zone, aLocale);
1667            } catch (IllegalArgumentException iae) {
1668                // fall back to the default instantiation
1669            }
1670        }
1671
1672        Calendar cal = null;
1673
1674        if (aLocale.hasExtensions()) {
1675            String caltype = aLocale.getUnicodeLocaleType("ca");
1676            if (caltype != null) {
1677                switch (caltype) {
1678                case "buddhist":
1679                cal = new BuddhistCalendar(zone, aLocale);
1680                    break;
1681                case "japanese":
1682                    cal = new JapaneseImperialCalendar(zone, aLocale);
1683                    break;
1684                case "gregory":
1685                    cal = new GregorianCalendar(zone, aLocale);
1686                    break;
1687                }
1688            }
1689        }
1690        if (cal == null) {
1691            // If no known calendar type is explicitly specified,
1692            // perform the traditional way to create a Calendar:
1693            // create a BuddhistCalendar for th_TH locale,
1694            // a JapaneseImperialCalendar for ja_JP_JP locale, or
1695            // a GregorianCalendar for any other locales.
1696            // NOTE: The language, country and variant strings are interned.
1697            if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") {
1698                cal = new BuddhistCalendar(zone, aLocale);
1699            } else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"
1700                       && aLocale.getCountry() == "JP") {
1701                cal = new JapaneseImperialCalendar(zone, aLocale);
1702            } else {
1703                cal = new GregorianCalendar(zone, aLocale);
1704            }
1705        }
1706        return cal;
1707    }
1708
1709    /**
1710     * Returns an array of all locales for which the <code>getInstance</code>
1711     * methods of this class can return localized instances.
1712     * The array returned must contain at least a <code>Locale</code>
1713     * instance equal to {@link java.util.Locale#US Locale.US}.
1714     *
1715     * @return An array of locales for which localized
1716     *         <code>Calendar</code> instances are available.
1717     */
1718    public static synchronized Locale[] getAvailableLocales()
1719    {
1720        return DateFormat.getAvailableLocales();
1721    }
1722
1723    /**
1724     * Converts the current calendar field values in {@link #fields fields[]}
1725     * to the millisecond time value
1726     * {@link #time}.
1727     *
1728     * @see #complete()
1729     * @see #computeFields()
1730     */
1731    protected abstract void computeTime();
1732
1733    /**
1734     * Converts the current millisecond time value {@link #time}
1735     * to calendar field values in {@link #fields fields[]}.
1736     * This allows you to sync up the calendar field values with
1737     * a new time that is set for the calendar.  The time is <em>not</em>
1738     * recomputed first; to recompute the time, then the fields, call the
1739     * {@link #complete()} method.
1740     *
1741     * @see #computeTime()
1742     */
1743    protected abstract void computeFields();
1744
1745    /**
1746     * Returns a <code>Date</code> object representing this
1747     * <code>Calendar</code>'s time value (millisecond offset from the <a
1748     * href="#Epoch">Epoch</a>").
1749     *
1750     * @return a <code>Date</code> representing the time value.
1751     * @see #setTime(Date)
1752     * @see #getTimeInMillis()
1753     */
1754    public final Date getTime() {
1755        return new Date(getTimeInMillis());
1756    }
1757
1758    /**
1759     * Sets this Calendar's time with the given <code>Date</code>.
1760     * <p>
1761     * Note: Calling <code>setTime()</code> with
1762     * <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code>
1763     * may yield incorrect field values from <code>get()</code>.
1764     *
1765     * @param date the given Date.
1766     * @see #getTime()
1767     * @see #setTimeInMillis(long)
1768     */
1769    public final void setTime(Date date) {
1770        setTimeInMillis(date.getTime());
1771    }
1772
1773    /**
1774     * Returns this Calendar's time value in milliseconds.
1775     *
1776     * @return the current time as UTC milliseconds from the epoch.
1777     * @see #getTime()
1778     * @see #setTimeInMillis(long)
1779     */
1780    public long getTimeInMillis() {
1781        if (!isTimeSet) {
1782            updateTime();
1783        }
1784        return time;
1785    }
1786
1787    /**
1788     * Sets this Calendar's current time from the given long value.
1789     *
1790     * @param millis the new time in UTC milliseconds from the epoch.
1791     * @see #setTime(Date)
1792     * @see #getTimeInMillis()
1793     */
1794    public void setTimeInMillis(long millis) {
1795        // If we don't need to recalculate the calendar field values,
1796        // do nothing.
1797        if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet
1798            && (zone instanceof ZoneInfo) && !((ZoneInfo)zone).isDirty()) {
1799            return;
1800        }
1801        time = millis;
1802        isTimeSet = true;
1803        areFieldsSet = false;
1804        computeFields();
1805        areAllFieldsSet = areFieldsSet = true;
1806    }
1807
1808    /**
1809     * Returns the value of the given calendar field. In lenient mode,
1810     * all calendar fields are normalized. In non-lenient mode, all
1811     * calendar fields are validated and this method throws an
1812     * exception if any calendar fields have out-of-range values. The
1813     * normalization and validation are handled by the
1814     * {@link #complete()} method, which process is calendar
1815     * system dependent.
1816     *
1817     * @param field the given calendar field.
1818     * @return the value for the given calendar field.
1819     * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
1820     *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1821     * @see #set(int,int)
1822     * @see #complete()
1823     */
1824    public int get(int field)
1825    {
1826        complete();
1827        return internalGet(field);
1828    }
1829
1830    /**
1831     * Returns the value of the given calendar field. This method does
1832     * not involve normalization or validation of the field value.
1833     *
1834     * @param field the given calendar field.
1835     * @return the value for the given calendar field.
1836     * @see #get(int)
1837     */
1838    protected final int internalGet(int field)
1839    {
1840        return fields[field];
1841    }
1842
1843    /**
1844     * Sets the value of the given calendar field. This method does
1845     * not affect any setting state of the field in this
1846     * <code>Calendar</code> instance.
1847     *
1848     * @throws IndexOutOfBoundsException if the specified field is out of range
1849     *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1850     * @see #areFieldsSet
1851     * @see #isTimeSet
1852     * @see #areAllFieldsSet
1853     * @see #set(int,int)
1854     */
1855    final void internalSet(int field, int value)
1856    {
1857        fields[field] = value;
1858    }
1859
1860    /**
1861     * Sets the given calendar field to the given value. The value is not
1862     * interpreted by this method regardless of the leniency mode.
1863     *
1864     * @param field the given calendar field.
1865     * @param value the value to be set for the given calendar field.
1866     * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
1867     *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1868     * in non-lenient mode.
1869     * @see #set(int,int,int)
1870     * @see #set(int,int,int,int,int)
1871     * @see #set(int,int,int,int,int,int)
1872     * @see #get(int)
1873     */
1874    public void set(int field, int value)
1875    {
1876        // If the fields are partially normalized, calculate all the
1877        // fields before changing any fields.
1878        if (areFieldsSet && !areAllFieldsSet) {
1879            computeFields();
1880        }
1881        internalSet(field, value);
1882        isTimeSet = false;
1883        areFieldsSet = false;
1884        isSet[field] = true;
1885        stamp[field] = nextStamp++;
1886        if (nextStamp == Integer.MAX_VALUE) {
1887            adjustStamp();
1888        }
1889    }
1890
1891    /**
1892     * Sets the values for the calendar fields <code>YEAR</code>,
1893     * <code>MONTH</code>, and <code>DAY_OF_MONTH</code>.
1894     * Previous values of other calendar fields are retained.  If this is not desired,
1895     * call {@link #clear()} first.
1896     *
1897     * @param year the value used to set the <code>YEAR</code> calendar field.
1898     * @param month the value used to set the <code>MONTH</code> calendar field.
1899     * Month value is 0-based. e.g., 0 for January.
1900     * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1901     * @see #set(int,int)
1902     * @see #set(int,int,int,int,int)
1903     * @see #set(int,int,int,int,int,int)
1904     */
1905    public final void set(int year, int month, int date)
1906    {
1907        set(YEAR, year);
1908        set(MONTH, month);
1909        set(DATE, date);
1910    }
1911
1912    /**
1913     * Sets the values for the calendar fields <code>YEAR</code>,
1914     * <code>MONTH</code>, <code>DAY_OF_MONTH</code>,
1915     * <code>HOUR_OF_DAY</code>, and <code>MINUTE</code>.
1916     * Previous values of other fields are retained.  If this is not desired,
1917     * call {@link #clear()} first.
1918     *
1919     * @param year the value used to set the <code>YEAR</code> calendar field.
1920     * @param month the value used to set the <code>MONTH</code> calendar field.
1921     * Month value is 0-based. e.g., 0 for January.
1922     * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1923     * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
1924     * @param minute the value used to set the <code>MINUTE</code> calendar field.
1925     * @see #set(int,int)
1926     * @see #set(int,int,int)
1927     * @see #set(int,int,int,int,int,int)
1928     */
1929    public final void set(int year, int month, int date, int hourOfDay, int minute)
1930    {
1931        set(YEAR, year);
1932        set(MONTH, month);
1933        set(DATE, date);
1934        set(HOUR_OF_DAY, hourOfDay);
1935        set(MINUTE, minute);
1936    }
1937
1938    /**
1939     * Sets the values for the fields <code>YEAR</code>, <code>MONTH</code>,
1940     * <code>DAY_OF_MONTH</code>, <code>HOUR_OF_DAY</code>, <code>MINUTE</code>, and
1941     * <code>SECOND</code>.
1942     * Previous values of other fields are retained.  If this is not desired,
1943     * call {@link #clear()} first.
1944     *
1945     * @param year the value used to set the <code>YEAR</code> calendar field.
1946     * @param month the value used to set the <code>MONTH</code> calendar field.
1947     * Month value is 0-based. e.g., 0 for January.
1948     * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1949     * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
1950     * @param minute the value used to set the <code>MINUTE</code> calendar field.
1951     * @param second the value used to set the <code>SECOND</code> calendar field.
1952     * @see #set(int,int)
1953     * @see #set(int,int,int)
1954     * @see #set(int,int,int,int,int)
1955     */
1956    public final void set(int year, int month, int date, int hourOfDay, int minute,
1957                          int second)
1958    {
1959        set(YEAR, year);
1960        set(MONTH, month);
1961        set(DATE, date);
1962        set(HOUR_OF_DAY, hourOfDay);
1963        set(MINUTE, minute);
1964        set(SECOND, second);
1965    }
1966
1967    /**
1968     * Sets all the calendar field values and the time value
1969     * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
1970     * this <code>Calendar</code> undefined. This means that {@link
1971     * #isSet(int) isSet()} will return <code>false</code> for all the
1972     * calendar fields, and the date and time calculations will treat
1973     * the fields as if they had never been set. A
1974     * <code>Calendar</code> implementation class may use its specific
1975     * default field values for date/time calculations. For example,
1976     * <code>GregorianCalendar</code> uses 1970 if the
1977     * <code>YEAR</code> field value is undefined.
1978     *
1979     * @see #clear(int)
1980     */
1981    public final void clear()
1982    {
1983        for (int i = 0; i < fields.length; ) {
1984            stamp[i] = fields[i] = 0; // UNSET == 0
1985            isSet[i++] = false;
1986        }
1987        areAllFieldsSet = areFieldsSet = false;
1988        isTimeSet = false;
1989    }
1990
1991    /**
1992     * Sets the given calendar field value and the time value
1993     * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
1994     * this <code>Calendar</code> undefined. This means that {@link
1995     * #isSet(int) isSet(field)} will return <code>false</code>, and
1996     * the date and time calculations will treat the field as if it
1997     * had never been set. A <code>Calendar</code> implementation
1998     * class may use the field's specific default value for date and
1999     * time calculations.
2000     *
2001     * <p>The {@link #HOUR_OF_DAY}, {@link #HOUR} and {@link #AM_PM}
2002     * fields are handled independently and the <a
2003     * href="#time_resolution">the resolution rule for the time of
2004     * day</a> is applied. Clearing one of the fields doesn't reset
2005     * the hour of day value of this <code>Calendar</code>. Use {@link
2006     * #set(int,int) set(Calendar.HOUR_OF_DAY, 0)} to reset the hour
2007     * value.
2008     *
2009     * @param field the calendar field to be cleared.
2010     * @see #clear()
2011     */
2012    public final void clear(int field)
2013    {
2014        fields[field] = 0;
2015        stamp[field] = UNSET;
2016        isSet[field] = false;
2017
2018        areAllFieldsSet = areFieldsSet = false;
2019        isTimeSet = false;
2020    }
2021
2022    /**
2023     * Determines if the given calendar field has a value set,
2024     * including cases that the value has been set by internal fields
2025     * calculations triggered by a <code>get</code> method call.
2026     *
2027     * @param field the calendar field to test
2028     * @return <code>true</code> if the given calendar field has a value set;
2029     * <code>false</code> otherwise.
2030     */
2031    public final boolean isSet(int field)
2032    {
2033        return stamp[field] != UNSET;
2034    }
2035
2036    /**
2037     * Returns the string representation of the calendar
2038     * <code>field</code> value in the given <code>style</code> and
2039     * <code>locale</code>.  If no string representation is
2040     * applicable, <code>null</code> is returned. This method calls
2041     * {@link Calendar#get(int) get(field)} to get the calendar
2042     * <code>field</code> value if the string representation is
2043     * applicable to the given calendar <code>field</code>.
2044     *
2045     * <p>For example, if this <code>Calendar</code> is a
2046     * <code>GregorianCalendar</code> and its date is 2005-01-01, then
2047     * the string representation of the {@link #MONTH} field would be
2048     * "January" in the long style in an English locale or "Jan" in
2049     * the short style. However, no string representation would be
2050     * available for the {@link #DAY_OF_MONTH} field, and this method
2051     * would return <code>null</code>.
2052     *
2053     * <p>The default implementation supports the calendar fields for
2054     * which a {@link DateFormatSymbols} has names in the given
2055     * <code>locale</code>.
2056     *
2057     * @param field
2058     *        the calendar field for which the string representation
2059     *        is returned
2060     * @param style
2061     *        the style applied to the string representation; one of {@link
2062     *        #SHORT_FORMAT} ({@link #SHORT}), {@link #SHORT_STANDALONE},
2063     *        {@link #LONG_FORMAT} ({@link #LONG}), {@link #LONG_STANDALONE},
2064     *        {@link #NARROW_FORMAT}, or {@link #NARROW_STANDALONE}.
2065     * @param locale
2066     *        the locale for the string representation
2067     *        (any calendar types specified by {@code locale} are ignored)
2068     * @return the string representation of the given
2069     *        {@code field} in the given {@code style}, or
2070     *        {@code null} if no string representation is
2071     *        applicable.
2072     * @exception IllegalArgumentException
2073     *        if {@code field} or {@code style} is invalid,
2074     *        or if this {@code Calendar} is non-lenient and any
2075     *        of the calendar fields have invalid values
2076     * @exception NullPointerException
2077     *        if {@code locale} is null
2078     * @since 1.6
2079     */
2080    public String getDisplayName(int field, int style, Locale locale) {
2081        if (!checkDisplayNameParams(field, style, SHORT, NARROW_FORMAT, locale,
2082                            ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
2083            return null;
2084        }
2085
2086        String calendarType = getCalendarType();
2087        int fieldValue = get(field);
2088        // the standalone and narrow styles are supported only through CalendarDataProviders.
2089        if (isStandaloneStyle(style) || isNarrowFormatStyle(style)) {
2090            String val = CalendarDataUtility.retrieveFieldValueName(calendarType,
2091                                                                    field, fieldValue,
2092                                                                    style, locale);
2093            // Perform fallback here to follow the CLDR rules
2094            if (val == null) {
2095                if (isNarrowFormatStyle(style)) {
2096                    val = CalendarDataUtility.retrieveFieldValueName(calendarType,
2097                                                                     field, fieldValue,
2098                                                                     toStandaloneStyle(style),
2099                                                                     locale);
2100                } else if (isStandaloneStyle(style)) {
2101                    val = CalendarDataUtility.retrieveFieldValueName(calendarType,
2102                                                                     field, fieldValue,
2103                                                                     getBaseStyle(style),
2104                                                                     locale);
2105                }
2106            }
2107            return val;
2108        }
2109
2110        DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
2111        String[] strings = getFieldStrings(field, style, symbols);
2112        if (strings != null) {
2113            if (fieldValue < strings.length) {
2114                return strings[fieldValue];
2115            }
2116        }
2117        return null;
2118    }
2119
2120    /**
2121     * Returns a {@code Map} containing all names of the calendar
2122     * {@code field} in the given {@code style} and
2123     * {@code locale} and their corresponding field values. For
2124     * example, if this {@code Calendar} is a {@link
2125     * GregorianCalendar}, the returned map would contain "Jan" to
2126     * {@link #JANUARY}, "Feb" to {@link #FEBRUARY}, and so on, in the
2127     * {@linkplain #SHORT short} style in an English locale.
2128     *
2129     * <p>Narrow names may not be unique due to use of single characters,
2130     * such as "S" for Sunday and Saturday. In that case narrow names are not
2131     * included in the returned {@code Map}.
2132     *
2133     * <p>The values of other calendar fields may be taken into
2134     * account to determine a set of display names. For example, if
2135     * this {@code Calendar} is a lunisolar calendar system and
2136     * the year value given by the {@link #YEAR} field has a leap
2137     * month, this method would return month names containing the leap
2138     * month name, and month names are mapped to their values specific
2139     * for the year.
2140     *
2141     * <p>The default implementation supports display names contained in
2142     * a {@link DateFormatSymbols}. For example, if {@code field}
2143     * is {@link #MONTH} and {@code style} is {@link
2144     * #ALL_STYLES}, this method returns a {@code Map} containing
2145     * all strings returned by {@link DateFormatSymbols#getShortMonths()}
2146     * and {@link DateFormatSymbols#getMonths()}.
2147     *
2148     * @param field
2149     *        the calendar field for which the display names are returned
2150     * @param style
2151     *        the style applied to the string representation; one of {@link
2152     *        #SHORT_FORMAT} ({@link #SHORT}), {@link #SHORT_STANDALONE},
2153     *        {@link #LONG_FORMAT} ({@link #LONG}), {@link #LONG_STANDALONE},
2154     *        {@link #NARROW_FORMAT}, or {@link #NARROW_STANDALONE}
2155     * @param locale
2156     *        the locale for the display names
2157     * @return a {@code Map} containing all display names in
2158     *        {@code style} and {@code locale} and their
2159     *        field values, or {@code null} if no display names
2160     *        are defined for {@code field}
2161     * @exception IllegalArgumentException
2162     *        if {@code field} or {@code style} is invalid,
2163     *        or if this {@code Calendar} is non-lenient and any
2164     *        of the calendar fields have invalid values
2165     * @exception NullPointerException
2166     *        if {@code locale} is null
2167     * @since 1.6
2168     */
2169    public Map<String, Integer> getDisplayNames(int field, int style, Locale locale) {
2170        if (!checkDisplayNameParams(field, style, ALL_STYLES, NARROW_FORMAT, locale,
2171                                    ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
2172            return null;
2173        }
2174
2175        String calendarType = getCalendarType();
2176        if (style == ALL_STYLES || isStandaloneStyle(style) || isNarrowFormatStyle(style)) {
2177            Map<String, Integer> map;
2178            map = CalendarDataUtility.retrieveFieldValueNames(calendarType, field, style, locale);
2179
2180            // Perform fallback here to follow the CLDR rules
2181            if (map == null) {
2182                if (isNarrowFormatStyle(style)) {
2183                    map = CalendarDataUtility.retrieveFieldValueNames(calendarType, field,
2184                                                                      toStandaloneStyle(style), locale);
2185                } else if (style != ALL_STYLES) {
2186                    map = CalendarDataUtility.retrieveFieldValueNames(calendarType, field,
2187                                                                      getBaseStyle(style), locale);
2188                }
2189            }
2190            return map;
2191        }
2192
2193        // SHORT or LONG
2194        return getDisplayNamesImpl(field, style, locale);
2195    }
2196
2197    private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) {
2198        DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
2199        String[] strings = getFieldStrings(field, style, symbols);
2200        if (strings != null) {
2201            Map<String,Integer> names = new HashMap<>();
2202            for (int i = 0; i < strings.length; i++) {
2203                if (strings[i].length() == 0) {
2204                    continue;
2205                }
2206                names.put(strings[i], i);
2207            }
2208            return names;
2209        }
2210        return null;
2211    }
2212
2213    boolean checkDisplayNameParams(int field, int style, int minStyle, int maxStyle,
2214                                   Locale locale, int fieldMask) {
2215        int baseStyle = getBaseStyle(style); // Ignore the standalone mask
2216        if (field < 0 || field >= fields.length ||
2217            baseStyle < minStyle || baseStyle > maxStyle) {
2218            throw new IllegalArgumentException();
2219        }
2220        if (locale == null) {
2221            throw new NullPointerException();
2222        }
2223        return isFieldSet(fieldMask, field);
2224    }
2225
2226    private String[] getFieldStrings(int field, int style, DateFormatSymbols symbols) {
2227        int baseStyle = getBaseStyle(style); // ignore the standalone mask
2228
2229        // DateFormatSymbols doesn't support any narrow names.
2230        if (baseStyle == NARROW_FORMAT) {
2231            return null;
2232        }
2233
2234        String[] strings = null;
2235        switch (field) {
2236        case ERA:
2237            strings = symbols.getEras();
2238            break;
2239
2240        case MONTH:
2241            strings = (baseStyle == LONG) ? symbols.getMonths() : symbols.getShortMonths();
2242            break;
2243
2244        case DAY_OF_WEEK:
2245            strings = (baseStyle == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays();
2246            break;
2247
2248        case AM_PM:
2249            strings = symbols.getAmPmStrings();
2250            break;
2251        }
2252        return strings;
2253    }
2254
2255    /**
2256     * Fills in any unset fields in the calendar fields. First, the {@link
2257     * #computeTime()} method is called if the time value (millisecond offset
2258     * from the <a href="#Epoch">Epoch</a>) has not been calculated from
2259     * calendar field values. Then, the {@link #computeFields()} method is
2260     * called to calculate all calendar field values.
2261     */
2262    protected void complete()
2263    {
2264        if (!isTimeSet) {
2265            updateTime();
2266        }
2267        if (!areFieldsSet || !areAllFieldsSet) {
2268            computeFields(); // fills in unset fields
2269            areAllFieldsSet = areFieldsSet = true;
2270        }
2271    }
2272
2273    /**
2274     * Returns whether the value of the specified calendar field has been set
2275     * externally by calling one of the setter methods rather than by the
2276     * internal time calculation.
2277     *
2278     * @return <code>true</code> if the field has been set externally,
2279     * <code>false</code> otherwise.
2280     * @exception IndexOutOfBoundsException if the specified
2281     *                <code>field</code> is out of range
2282     *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
2283     * @see #selectFields()
2284     * @see #setFieldsComputed(int)
2285     */
2286    final boolean isExternallySet(int field) {
2287        return stamp[field] >= MINIMUM_USER_STAMP;
2288    }
2289
2290    /**
2291     * Returns a field mask (bit mask) indicating all calendar fields that
2292     * have the state of externally or internally set.
2293     *
2294     * @return a bit mask indicating set state fields
2295     */
2296    final int getSetStateFields() {
2297        int mask = 0;
2298        for (int i = 0; i < fields.length; i++) {
2299            if (stamp[i] != UNSET) {
2300                mask |= 1 << i;
2301            }
2302        }
2303        return mask;
2304    }
2305
2306    /**
2307     * Sets the state of the specified calendar fields to
2308     * <em>computed</em>. This state means that the specified calendar fields
2309     * have valid values that have been set by internal time calculation
2310     * rather than by calling one of the setter methods.
2311     *
2312     * @param fieldMask the field to be marked as computed.
2313     * @exception IndexOutOfBoundsException if the specified
2314     *                <code>field</code> is out of range
2315     *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
2316     * @see #isExternallySet(int)
2317     * @see #selectFields()
2318     */
2319    final void setFieldsComputed(int fieldMask) {
2320        if (fieldMask == ALL_FIELDS) {
2321            for (int i = 0; i < fields.length; i++) {
2322                stamp[i] = COMPUTED;
2323                isSet[i] = true;
2324            }
2325            areFieldsSet = areAllFieldsSet = true;
2326        } else {
2327            for (int i = 0; i < fields.length; i++) {
2328                if ((fieldMask & 1) == 1) {
2329                    stamp[i] = COMPUTED;
2330                    isSet[i] = true;
2331                } else {
2332                    if (areAllFieldsSet && !isSet[i]) {
2333                        areAllFieldsSet = false;
2334                    }
2335                }
2336                fieldMask >>>= 1;
2337            }
2338        }
2339    }
2340
2341    /**
2342     * Sets the state of the calendar fields that are <em>not</em> specified
2343     * by <code>fieldMask</code> to <em>unset</em>. If <code>fieldMask</code>
2344     * specifies all the calendar fields, then the state of this
2345     * <code>Calendar</code> becomes that all the calendar fields are in sync
2346     * with the time value (millisecond offset from the Epoch).
2347     *
2348     * @param fieldMask the field mask indicating which calendar fields are in
2349     * sync with the time value.
2350     * @exception IndexOutOfBoundsException if the specified
2351     *                <code>field</code> is out of range
2352     *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
2353     * @see #isExternallySet(int)
2354     * @see #selectFields()
2355     */
2356    final void setFieldsNormalized(int fieldMask) {
2357        if (fieldMask != ALL_FIELDS) {
2358            for (int i = 0; i < fields.length; i++) {
2359                if ((fieldMask & 1) == 0) {
2360                    stamp[i] = fields[i] = 0; // UNSET == 0
2361                    isSet[i] = false;
2362                }
2363                fieldMask >>= 1;
2364            }
2365        }
2366
2367        // Some or all of the fields are in sync with the
2368        // milliseconds, but the stamp values are not normalized yet.
2369        areFieldsSet = true;
2370        areAllFieldsSet = false;
2371    }
2372
2373    /**
2374     * Returns whether the calendar fields are partially in sync with the time
2375     * value or fully in sync but not stamp values are not normalized yet.
2376     */
2377    final boolean isPartiallyNormalized() {
2378        return areFieldsSet && !areAllFieldsSet;
2379    }
2380
2381    /**
2382     * Returns whether the calendar fields are fully in sync with the time
2383     * value.
2384     */
2385    final boolean isFullyNormalized() {
2386        return areFieldsSet && areAllFieldsSet;
2387    }
2388
2389    /**
2390     * Marks this Calendar as not sync'd.
2391     */
2392    final void setUnnormalized() {
2393        areFieldsSet = areAllFieldsSet = false;
2394    }
2395
2396    /**
2397     * Returns whether the specified <code>field</code> is on in the
2398     * <code>fieldMask</code>.
2399     */
2400    static boolean isFieldSet(int fieldMask, int field) {
2401        return (fieldMask & (1 << field)) != 0;
2402    }
2403
2404    /**
2405     * Returns a field mask indicating which calendar field values
2406     * to be used to calculate the time value. The calendar fields are
2407     * returned as a bit mask, each bit of which corresponds to a field, i.e.,
2408     * the mask value of <code>field</code> is <code>(1 &lt;&lt;
2409     * field)</code>. For example, 0x26 represents the <code>YEAR</code>,
2410     * <code>MONTH</code>, and <code>DAY_OF_MONTH</code> fields (i.e., 0x26 is
2411     * equal to
2412     * <code>(1&lt;&lt;YEAR)|(1&lt;&lt;MONTH)|(1&lt;&lt;DAY_OF_MONTH))</code>.
2413     *
2414     * <p>This method supports the calendar fields resolution as described in
2415     * the class description. If the bit mask for a given field is on and its
2416     * field has not been set (i.e., <code>isSet(field)</code> is
2417     * <code>false</code>), then the default value of the field has to be
2418     * used, which case means that the field has been selected because the
2419     * selected combination involves the field.
2420     *
2421     * @return a bit mask of selected fields
2422     * @see #isExternallySet(int)
2423     */
2424    final int selectFields() {
2425        // This implementation has been taken from the GregorianCalendar class.
2426
2427        // The YEAR field must always be used regardless of its SET
2428        // state because YEAR is a mandatory field to determine the date
2429        // and the default value (EPOCH_YEAR) may change through the
2430        // normalization process.
2431        int fieldMask = YEAR_MASK;
2432
2433        if (stamp[ERA] != UNSET) {
2434            fieldMask |= ERA_MASK;
2435        }
2436        // Find the most recent group of fields specifying the day within
2437        // the year.  These may be any of the following combinations:
2438        //   MONTH + DAY_OF_MONTH
2439        //   MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
2440        //   MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
2441        //   DAY_OF_YEAR
2442        //   WEEK_OF_YEAR + DAY_OF_WEEK
2443        // We look for the most recent of the fields in each group to determine
2444        // the age of the group.  For groups involving a week-related field such
2445        // as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the
2446        // week-related field and the DAY_OF_WEEK must be set for the group as a
2447        // whole to be considered.  (See bug 4153860 - liu 7/24/98.)
2448        int dowStamp = stamp[DAY_OF_WEEK];
2449        int monthStamp = stamp[MONTH];
2450        int domStamp = stamp[DAY_OF_MONTH];
2451        int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp);
2452        int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
2453        int doyStamp = stamp[DAY_OF_YEAR];
2454        int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp);
2455
2456        int bestStamp = domStamp;
2457        if (womStamp > bestStamp) {
2458            bestStamp = womStamp;
2459        }
2460        if (dowimStamp > bestStamp) {
2461            bestStamp = dowimStamp;
2462        }
2463        if (doyStamp > bestStamp) {
2464            bestStamp = doyStamp;
2465        }
2466        if (woyStamp > bestStamp) {
2467            bestStamp = woyStamp;
2468        }
2469
2470        /* No complete combination exists.  Look for WEEK_OF_MONTH,
2471         * DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone.  Treat DAY_OF_WEEK alone
2472         * as DAY_OF_WEEK_IN_MONTH.
2473         */
2474        if (bestStamp == UNSET) {
2475            womStamp = stamp[WEEK_OF_MONTH];
2476            dowimStamp = Math.max(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
2477            woyStamp = stamp[WEEK_OF_YEAR];
2478            bestStamp = Math.max(Math.max(womStamp, dowimStamp), woyStamp);
2479
2480            /* Treat MONTH alone or no fields at all as DAY_OF_MONTH.  This may
2481             * result in bestStamp = domStamp = UNSET if no fields are set,
2482             * which indicates DAY_OF_MONTH.
2483             */
2484            if (bestStamp == UNSET) {
2485                bestStamp = domStamp = monthStamp;
2486            }
2487        }
2488
2489        if (bestStamp == domStamp ||
2490           (bestStamp == womStamp && stamp[WEEK_OF_MONTH] >= stamp[WEEK_OF_YEAR]) ||
2491           (bestStamp == dowimStamp && stamp[DAY_OF_WEEK_IN_MONTH] >= stamp[WEEK_OF_YEAR])) {
2492            fieldMask |= MONTH_MASK;
2493            if (bestStamp == domStamp) {
2494                fieldMask |= DAY_OF_MONTH_MASK;
2495            } else {
2496                assert (bestStamp == womStamp || bestStamp == dowimStamp);
2497                if (dowStamp != UNSET) {
2498                    fieldMask |= DAY_OF_WEEK_MASK;
2499                }
2500                if (womStamp == dowimStamp) {
2501                    // When they are equal, give the priority to
2502                    // WEEK_OF_MONTH for compatibility.
2503                    if (stamp[WEEK_OF_MONTH] >= stamp[DAY_OF_WEEK_IN_MONTH]) {
2504                        fieldMask |= WEEK_OF_MONTH_MASK;
2505                    } else {
2506                        fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
2507                    }
2508                } else {
2509                    if (bestStamp == womStamp) {
2510                        fieldMask |= WEEK_OF_MONTH_MASK;
2511                    } else {
2512                        assert (bestStamp == dowimStamp);
2513                        if (stamp[DAY_OF_WEEK_IN_MONTH] != UNSET) {
2514                            fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
2515                        }
2516                    }
2517                }
2518            }
2519        } else {
2520            assert (bestStamp == doyStamp || bestStamp == woyStamp ||
2521                    bestStamp == UNSET);
2522            if (bestStamp == doyStamp) {
2523                fieldMask |= DAY_OF_YEAR_MASK;
2524            } else {
2525                assert (bestStamp == woyStamp);
2526                if (dowStamp != UNSET) {
2527                    fieldMask |= DAY_OF_WEEK_MASK;
2528                }
2529                fieldMask |= WEEK_OF_YEAR_MASK;
2530            }
2531        }
2532
2533        // Find the best set of fields specifying the time of day.  There
2534        // are only two possibilities here; the HOUR_OF_DAY or the
2535        // AM_PM and the HOUR.
2536        int hourOfDayStamp = stamp[HOUR_OF_DAY];
2537        int hourStamp = aggregateStamp(stamp[HOUR], stamp[AM_PM]);
2538        bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
2539
2540        // if bestStamp is still UNSET, then take HOUR or AM_PM. (See 4846659)
2541        if (bestStamp == UNSET) {
2542            bestStamp = Math.max(stamp[HOUR], stamp[AM_PM]);
2543        }
2544
2545        // Hours
2546        if (bestStamp != UNSET) {
2547            if (bestStamp == hourOfDayStamp) {
2548                fieldMask |= HOUR_OF_DAY_MASK;
2549            } else {
2550                fieldMask |= HOUR_MASK;
2551                if (stamp[AM_PM] != UNSET) {
2552                    fieldMask |= AM_PM_MASK;
2553                }
2554            }
2555        }
2556        if (stamp[MINUTE] != UNSET) {
2557            fieldMask |= MINUTE_MASK;
2558        }
2559        if (stamp[SECOND] != UNSET) {
2560            fieldMask |= SECOND_MASK;
2561        }
2562        if (stamp[MILLISECOND] != UNSET) {
2563            fieldMask |= MILLISECOND_MASK;
2564        }
2565        if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) {
2566                fieldMask |= ZONE_OFFSET_MASK;
2567        }
2568        if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) {
2569            fieldMask |= DST_OFFSET_MASK;
2570        }
2571
2572        return fieldMask;
2573    }
2574
2575    int getBaseStyle(int style) {
2576        return style & ~STANDALONE_MASK;
2577    }
2578
2579    private int toStandaloneStyle(int style) {
2580        return style | STANDALONE_MASK;
2581    }
2582
2583    private boolean isStandaloneStyle(int style) {
2584        return (style & STANDALONE_MASK) != 0;
2585    }
2586
2587    private boolean isNarrowStyle(int style) {
2588        return style == NARROW_FORMAT || style == NARROW_STANDALONE;
2589    }
2590
2591    private boolean isNarrowFormatStyle(int style) {
2592        return style == NARROW_FORMAT;
2593    }
2594
2595    /**
2596     * Returns the pseudo-time-stamp for two fields, given their
2597     * individual pseudo-time-stamps.  If either of the fields
2598     * is unset, then the aggregate is unset.  Otherwise, the
2599     * aggregate is the later of the two stamps.
2600     */
2601    private static int aggregateStamp(int stamp_a, int stamp_b) {
2602        if (stamp_a == UNSET || stamp_b == UNSET) {
2603            return UNSET;
2604        }
2605        return (stamp_a > stamp_b) ? stamp_a : stamp_b;
2606    }
2607
2608    /**
2609     * Returns an unmodifiable {@code Set} containing all calendar types
2610     * supported by {@code Calendar} in the runtime environment. The available
2611     * calendar types can be used for the <a
2612     * href="Locale.html#def_locale_extension">Unicode locale extensions</a>.
2613     * The {@code Set} returned contains at least {@code "gregory"}. The
2614     * calendar types don't include aliases, such as {@code "gregorian"} for
2615     * {@code "gregory"}.
2616     *
2617     * @return an unmodifiable {@code Set} containing all available calendar types
2618     * @since 1.8
2619     * @see #getCalendarType()
2620     * @see Calendar.Builder#setCalendarType(String)
2621     * @see Locale#getUnicodeLocaleType(String)
2622     */
2623    public static Set<String> getAvailableCalendarTypes() {
2624        return AvailableCalendarTypes.SET;
2625    }
2626
2627    private static class AvailableCalendarTypes {
2628        private static final Set<String> SET;
2629        static {
2630            Set<String> set = new HashSet<>(3);
2631            set.add("gregory");
2632            set.add("buddhist");
2633            set.add("japanese");
2634            SET = Collections.unmodifiableSet(set);
2635        }
2636        private AvailableCalendarTypes() {
2637        }
2638    }
2639
2640    /**
2641     * Returns the calendar type of this {@code Calendar}. Calendar types are
2642     * defined by the <em>Unicode Locale Data Markup Language (LDML)</em>
2643     * specification.
2644     *
2645     * <p>The default implementation of this method returns the class name of
2646     * this {@code Calendar} instance. Any subclasses that implement
2647     * LDML-defined calendar systems should override this method to return
2648     * appropriate calendar types.
2649     *
2650     * @return the LDML-defined calendar type or the class name of this
2651     *         {@code Calendar} instance
2652     * @since 1.8
2653     * @see <a href="Locale.html#def_extensions">Locale extensions</a>
2654     * @see Locale.Builder#setLocale(Locale)
2655     * @see Locale.Builder#setUnicodeLocaleKeyword(String, String)
2656     */
2657    public String getCalendarType() {
2658        return this.getClass().getName();
2659    }
2660
2661    /**
2662     * Compares this <code>Calendar</code> to the specified
2663     * <code>Object</code>.  The result is <code>true</code> if and only if
2664     * the argument is a <code>Calendar</code> object of the same calendar
2665     * system that represents the same time value (millisecond offset from the
2666     * <a href="#Epoch">Epoch</a>) under the same
2667     * <code>Calendar</code> parameters as this object.
2668     *
2669     * <p>The <code>Calendar</code> parameters are the values represented
2670     * by the <code>isLenient</code>, <code>getFirstDayOfWeek</code>,
2671     * <code>getMinimalDaysInFirstWeek</code> and <code>getTimeZone</code>
2672     * methods. If there is any difference in those parameters
2673     * between the two <code>Calendar</code>s, this method returns
2674     * <code>false</code>.
2675     *
2676     * <p>Use the {@link #compareTo(Calendar) compareTo} method to
2677     * compare only the time values.
2678     *
2679     * @param obj the object to compare with.
2680     * @return <code>true</code> if this object is equal to <code>obj</code>;
2681     * <code>false</code> otherwise.
2682     */
2683    @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
2684    @Override
2685    public boolean equals(Object obj) {
2686        if (this == obj) {
2687            return true;
2688        }
2689        try {
2690            Calendar that = (Calendar)obj;
2691            return compareTo(getMillisOf(that)) == 0 &&
2692                lenient == that.lenient &&
2693                firstDayOfWeek == that.firstDayOfWeek &&
2694                minimalDaysInFirstWeek == that.minimalDaysInFirstWeek &&
2695                zone.equals(that.zone);
2696        } catch (Exception e) {
2697            // Note: GregorianCalendar.computeTime throws
2698            // IllegalArgumentException if the ERA value is invalid
2699            // even it's in lenient mode.
2700        }
2701        return false;
2702    }
2703
2704    /**
2705     * Returns a hash code for this calendar.
2706     *
2707     * @return a hash code value for this object.
2708     * @since 1.2
2709     */
2710    @Override
2711    public int hashCode() {
2712        // 'otheritems' represents the hash code for the previous versions.
2713        int otheritems = (lenient ? 1 : 0)
2714            | (firstDayOfWeek << 1)
2715            | (minimalDaysInFirstWeek << 4)
2716            | (zone.hashCode() << 7);
2717        long t = getMillisOf(this);
2718        return (int) t ^ (int)(t >> 32) ^ otheritems;
2719    }
2720
2721    /**
2722     * Returns whether this <code>Calendar</code> represents a time
2723     * before the time represented by the specified
2724     * <code>Object</code>. This method is equivalent to:
2725     * <pre>{@code
2726     *         compareTo(when) < 0
2727     * }</pre>
2728     * if and only if <code>when</code> is a <code>Calendar</code>
2729     * instance. Otherwise, the method returns <code>false</code>.
2730     *
2731     * @param when the <code>Object</code> to be compared
2732     * @return <code>true</code> if the time of this
2733     * <code>Calendar</code> is before the time represented by
2734     * <code>when</code>; <code>false</code> otherwise.
2735     * @see     #compareTo(Calendar)
2736     */
2737    public boolean before(Object when) {
2738        return when instanceof Calendar
2739            && compareTo((Calendar)when) < 0;
2740    }
2741
2742    /**
2743     * Returns whether this <code>Calendar</code> represents a time
2744     * after the time represented by the specified
2745     * <code>Object</code>. This method is equivalent to:
2746     * <pre>{@code
2747     *         compareTo(when) > 0
2748     * }</pre>
2749     * if and only if <code>when</code> is a <code>Calendar</code>
2750     * instance. Otherwise, the method returns <code>false</code>.
2751     *
2752     * @param when the <code>Object</code> to be compared
2753     * @return <code>true</code> if the time of this <code>Calendar</code> is
2754     * after the time represented by <code>when</code>; <code>false</code>
2755     * otherwise.
2756     * @see     #compareTo(Calendar)
2757     */
2758    public boolean after(Object when) {
2759        return when instanceof Calendar
2760            && compareTo((Calendar)when) > 0;
2761    }
2762
2763    /**
2764     * Compares the time values (millisecond offsets from the <a
2765     * href="#Epoch">Epoch</a>) represented by two
2766     * <code>Calendar</code> objects.
2767     *
2768     * @param anotherCalendar the <code>Calendar</code> to be compared.
2769     * @return the value <code>0</code> if the time represented by the argument
2770     * is equal to the time represented by this <code>Calendar</code>; a value
2771     * less than <code>0</code> if the time of this <code>Calendar</code> is
2772     * before the time represented by the argument; and a value greater than
2773     * <code>0</code> if the time of this <code>Calendar</code> is after the
2774     * time represented by the argument.
2775     * @exception NullPointerException if the specified <code>Calendar</code> is
2776     *            <code>null</code>.
2777     * @exception IllegalArgumentException if the time value of the
2778     * specified <code>Calendar</code> object can't be obtained due to
2779     * any invalid calendar values.
2780     * @since   1.5
2781     */
2782    @Override
2783    public int compareTo(Calendar anotherCalendar) {
2784        return compareTo(getMillisOf(anotherCalendar));
2785    }
2786
2787    /**
2788     * Adds or subtracts the specified amount of time to the given calendar field,
2789     * based on the calendar's rules. For example, to subtract 5 days from
2790     * the current time of the calendar, you can achieve it by calling:
2791     * <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>.
2792     *
2793     * @param field the calendar field.
2794     * @param amount the amount of date or time to be added to the field.
2795     * @see #roll(int,int)
2796     * @see #set(int,int)
2797     */
2798    public abstract void add(int field, int amount);
2799
2800    /**
2801     * Adds or subtracts (up/down) a single unit of time on the given time
2802     * field without changing larger fields. For example, to roll the current
2803     * date up by one day, you can achieve it by calling:
2804     * <p>roll(Calendar.DATE, true).
2805     * When rolling on the year or Calendar.YEAR field, it will roll the year
2806     * value in the range between 1 and the value returned by calling
2807     * <code>getMaximum(Calendar.YEAR)</code>.
2808     * When rolling on the month or Calendar.MONTH field, other fields like
2809     * date might conflict and, need to be changed. For instance,
2810     * rolling the month on the date 01/31/96 will result in 02/29/96.
2811     * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will
2812     * roll the hour value in the range between 0 and 23, which is zero-based.
2813     *
2814     * @param field the time field.
2815     * @param up indicates if the value of the specified time field is to be
2816     * rolled up or rolled down. Use true if rolling up, false otherwise.
2817     * @see Calendar#add(int,int)
2818     * @see Calendar#set(int,int)
2819     */
2820    public abstract void roll(int field, boolean up);
2821
2822    /**
2823     * Adds the specified (signed) amount to the specified calendar field
2824     * without changing larger fields.  A negative amount means to roll
2825     * down.
2826     *
2827     * <p>NOTE:  This default implementation on <code>Calendar</code> just repeatedly calls the
2828     * version of {@link #roll(int,boolean) roll()} that rolls by one unit.  This may not
2829     * always do the right thing.  For example, if the <code>DAY_OF_MONTH</code> field is 31,
2830     * rolling through February will leave it set to 28.  The <code>GregorianCalendar</code>
2831     * version of this function takes care of this problem.  Other subclasses
2832     * should also provide overrides of this function that do the right thing.
2833     *
2834     * @param field the calendar field.
2835     * @param amount the signed amount to add to the calendar <code>field</code>.
2836     * @since 1.2
2837     * @see #roll(int,boolean)
2838     * @see #add(int,int)
2839     * @see #set(int,int)
2840     */
2841    public void roll(int field, int amount)
2842    {
2843        while (amount > 0) {
2844            roll(field, true);
2845            amount--;
2846        }
2847        while (amount < 0) {
2848            roll(field, false);
2849            amount++;
2850        }
2851    }
2852
2853    /**
2854     * Sets the time zone with the given time zone value.
2855     *
2856     * @param value the given time zone.
2857     */
2858    public void setTimeZone(TimeZone value)
2859    {
2860        zone = value;
2861        sharedZone = false;
2862        /* Recompute the fields from the time using the new zone.  This also
2863         * works if isTimeSet is false (after a call to set()).  In that case
2864         * the time will be computed from the fields using the new zone, then
2865         * the fields will get recomputed from that.  Consider the sequence of
2866         * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
2867         * Is cal set to 1 o'clock EST or 1 o'clock PST?  Answer: PST.  More
2868         * generally, a call to setTimeZone() affects calls to set() BEFORE AND
2869         * AFTER it up to the next call to complete().
2870         */
2871        areAllFieldsSet = areFieldsSet = false;
2872    }
2873
2874    /**
2875     * Gets the time zone.
2876     *
2877     * @return the time zone object associated with this calendar.
2878     */
2879    public TimeZone getTimeZone()
2880    {
2881        // If the TimeZone object is shared by other Calendar instances, then
2882        // create a clone.
2883        if (sharedZone) {
2884            zone = (TimeZone) zone.clone();
2885            sharedZone = false;
2886        }
2887        return zone;
2888    }
2889
2890    /**
2891     * Returns the time zone (without cloning).
2892     */
2893    TimeZone getZone() {
2894        return zone;
2895    }
2896
2897    /**
2898     * Sets the sharedZone flag to <code>shared</code>.
2899     */
2900    void setZoneShared(boolean shared) {
2901        sharedZone = shared;
2902    }
2903
2904    /**
2905     * Specifies whether or not date/time interpretation is to be lenient.  With
2906     * lenient interpretation, a date such as "February 942, 1996" will be
2907     * treated as being equivalent to the 941st day after February 1, 1996.
2908     * With strict (non-lenient) interpretation, such dates will cause an exception to be
2909     * thrown. The default is lenient.
2910     *
2911     * @param lenient <code>true</code> if the lenient mode is to be turned
2912     * on; <code>false</code> if it is to be turned off.
2913     * @see #isLenient()
2914     * @see java.text.DateFormat#setLenient
2915     */
2916    public void setLenient(boolean lenient)
2917    {
2918        this.lenient = lenient;
2919    }
2920
2921    /**
2922     * Tells whether date/time interpretation is to be lenient.
2923     *
2924     * @return <code>true</code> if the interpretation mode of this calendar is lenient;
2925     * <code>false</code> otherwise.
2926     * @see #setLenient(boolean)
2927     */
2928    public boolean isLenient()
2929    {
2930        return lenient;
2931    }
2932
2933    /**
2934     * Sets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
2935     * <code>MONDAY</code> in France.
2936     *
2937     * @param value the given first day of the week.
2938     * @see #getFirstDayOfWeek()
2939     * @see #getMinimalDaysInFirstWeek()
2940     */
2941    public void setFirstDayOfWeek(int value)
2942    {
2943        if (firstDayOfWeek == value) {
2944            return;
2945        }
2946        firstDayOfWeek = value;
2947        invalidateWeekFields();
2948    }
2949
2950    /**
2951     * Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
2952     * <code>MONDAY</code> in France.
2953     *
2954     * @return the first day of the week.
2955     * @see #setFirstDayOfWeek(int)
2956     * @see #getMinimalDaysInFirstWeek()
2957     */
2958    public int getFirstDayOfWeek()
2959    {
2960        return firstDayOfWeek;
2961    }
2962
2963    /**
2964     * Sets what the minimal days required in the first week of the year are;
2965     * For example, if the first week is defined as one that contains the first
2966     * day of the first month of a year, call this method with value 1. If it
2967     * must be a full week, use value 7.
2968     *
2969     * @param value the given minimal days required in the first week
2970     * of the year.
2971     * @see #getMinimalDaysInFirstWeek()
2972     */
2973    public void setMinimalDaysInFirstWeek(int value)
2974    {
2975        if (minimalDaysInFirstWeek == value) {
2976            return;
2977        }
2978        minimalDaysInFirstWeek = value;
2979        invalidateWeekFields();
2980    }
2981
2982    /**
2983     * Gets what the minimal days required in the first week of the year are;
2984     * e.g., if the first week is defined as one that contains the first day
2985     * of the first month of a year, this method returns 1. If
2986     * the minimal days required must be a full week, this method
2987     * returns 7.
2988     *
2989     * @return the minimal days required in the first week of the year.
2990     * @see #setMinimalDaysInFirstWeek(int)
2991     */
2992    public int getMinimalDaysInFirstWeek()
2993    {
2994        return minimalDaysInFirstWeek;
2995    }
2996
2997    /**
2998     * Returns whether this {@code Calendar} supports week dates.
2999     *
3000     * <p>The default implementation of this method returns {@code false}.
3001     *
3002     * @return {@code true} if this {@code Calendar} supports week dates;
3003     *         {@code false} otherwise.
3004     * @see #getWeekYear()
3005     * @see #setWeekDate(int,int,int)
3006     * @see #getWeeksInWeekYear()
3007     * @since 1.7
3008     */
3009    public boolean isWeekDateSupported() {
3010        return false;
3011    }
3012
3013    /**
3014     * Returns the week year represented by this {@code Calendar}. The
3015     * week year is in sync with the week cycle. The {@linkplain
3016     * #getFirstDayOfWeek() first day of the first week} is the first
3017     * day of the week year.
3018     *
3019     * <p>The default implementation of this method throws an
3020     * {@link UnsupportedOperationException}.
3021     *
3022     * @return the week year of this {@code Calendar}
3023     * @exception UnsupportedOperationException
3024     *            if any week year numbering isn't supported
3025     *            in this {@code Calendar}.
3026     * @see #isWeekDateSupported()
3027     * @see #getFirstDayOfWeek()
3028     * @see #getMinimalDaysInFirstWeek()
3029     * @since 1.7
3030     */
3031    public int getWeekYear() {
3032        throw new UnsupportedOperationException();
3033    }
3034
3035    /**
3036     * Sets the date of this {@code Calendar} with the given date
3037     * specifiers - week year, week of year, and day of week.
3038     *
3039     * <p>Unlike the {@code set} method, all of the calendar fields
3040     * and {@code time} values are calculated upon return.
3041     *
3042     * <p>If {@code weekOfYear} is out of the valid week-of-year range
3043     * in {@code weekYear}, the {@code weekYear} and {@code
3044     * weekOfYear} values are adjusted in lenient mode, or an {@code
3045     * IllegalArgumentException} is thrown in non-lenient mode.
3046     *
3047     * <p>The default implementation of this method throws an
3048     * {@code UnsupportedOperationException}.
3049     *
3050     * @param weekYear   the week year
3051     * @param weekOfYear the week number based on {@code weekYear}
3052     * @param dayOfWeek  the day of week value: one of the constants
3053     *                   for the {@link #DAY_OF_WEEK} field: {@link
3054     *                   #SUNDAY}, ..., {@link #SATURDAY}.
3055     * @exception IllegalArgumentException
3056     *            if any of the given date specifiers is invalid
3057     *            or any of the calendar fields are inconsistent
3058     *            with the given date specifiers in non-lenient mode
3059     * @exception UnsupportedOperationException
3060     *            if any week year numbering isn't supported in this
3061     *            {@code Calendar}.
3062     * @see #isWeekDateSupported()
3063     * @see #getFirstDayOfWeek()
3064     * @see #getMinimalDaysInFirstWeek()
3065     * @since 1.7
3066     */
3067    public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
3068        throw new UnsupportedOperationException();
3069    }
3070
3071    /**
3072     * Returns the number of weeks in the week year represented by this
3073     * {@code Calendar}.
3074     *
3075     * <p>The default implementation of this method throws an
3076     * {@code UnsupportedOperationException}.
3077     *
3078     * @return the number of weeks in the week year.
3079     * @exception UnsupportedOperationException
3080     *            if any week year numbering isn't supported in this
3081     *            {@code Calendar}.
3082     * @see #WEEK_OF_YEAR
3083     * @see #isWeekDateSupported()
3084     * @see #getWeekYear()
3085     * @see #getActualMaximum(int)
3086     * @since 1.7
3087     */
3088    public int getWeeksInWeekYear() {
3089        throw new UnsupportedOperationException();
3090    }
3091
3092    /**
3093     * Returns the minimum value for the given calendar field of this
3094     * <code>Calendar</code> instance. The minimum value is defined as
3095     * the smallest value returned by the {@link #get(int) get} method
3096     * for any possible time value.  The minimum value depends on
3097     * calendar system specific parameters of the instance.
3098     *
3099     * @param field the calendar field.
3100     * @return the minimum value for the given calendar field.
3101     * @see #getMaximum(int)
3102     * @see #getGreatestMinimum(int)
3103     * @see #getLeastMaximum(int)
3104     * @see #getActualMinimum(int)
3105     * @see #getActualMaximum(int)
3106     */
3107    public abstract int getMinimum(int field);
3108
3109    /**
3110     * Returns the maximum value for the given calendar field of this
3111     * <code>Calendar</code> instance. The maximum value is defined as
3112     * the largest value returned by the {@link #get(int) get} method
3113     * for any possible time value. The maximum value depends on
3114     * calendar system specific parameters of the instance.
3115     *
3116     * @param field the calendar field.
3117     * @return the maximum value for the given calendar field.
3118     * @see #getMinimum(int)
3119     * @see #getGreatestMinimum(int)
3120     * @see #getLeastMaximum(int)
3121     * @see #getActualMinimum(int)
3122     * @see #getActualMaximum(int)
3123     */
3124    public abstract int getMaximum(int field);
3125
3126    /**
3127     * Returns the highest minimum value for the given calendar field
3128     * of this <code>Calendar</code> instance. The highest minimum
3129     * value is defined as the largest value returned by {@link
3130     * #getActualMinimum(int)} for any possible time value. The
3131     * greatest minimum value depends on calendar system specific
3132     * parameters of the instance.
3133     *
3134     * @param field the calendar field.
3135     * @return the highest minimum value for the given calendar field.
3136     * @see #getMinimum(int)
3137     * @see #getMaximum(int)
3138     * @see #getLeastMaximum(int)
3139     * @see #getActualMinimum(int)
3140     * @see #getActualMaximum(int)
3141     */
3142    public abstract int getGreatestMinimum(int field);
3143
3144    /**
3145     * Returns the lowest maximum value for the given calendar field
3146     * of this <code>Calendar</code> instance. The lowest maximum
3147     * value is defined as the smallest value returned by {@link
3148     * #getActualMaximum(int)} for any possible time value. The least
3149     * maximum value depends on calendar system specific parameters of
3150     * the instance. For example, a <code>Calendar</code> for the
3151     * Gregorian calendar system returns 28 for the
3152     * <code>DAY_OF_MONTH</code> field, because the 28th is the last
3153     * day of the shortest month of this calendar, February in a
3154     * common year.
3155     *
3156     * @param field the calendar field.
3157     * @return the lowest maximum value for the given calendar field.
3158     * @see #getMinimum(int)
3159     * @see #getMaximum(int)
3160     * @see #getGreatestMinimum(int)
3161     * @see #getActualMinimum(int)
3162     * @see #getActualMaximum(int)
3163     */
3164    public abstract int getLeastMaximum(int field);
3165
3166    /**
3167     * Returns the minimum value that the specified calendar field
3168     * could have, given the time value of this <code>Calendar</code>.
3169     *
3170     * <p>The default implementation of this method uses an iterative
3171     * algorithm to determine the actual minimum value for the
3172     * calendar field. Subclasses should, if possible, override this
3173     * with a more efficient implementation - in many cases, they can
3174     * simply return <code>getMinimum()</code>.
3175     *
3176     * @param field the calendar field
3177     * @return the minimum of the given calendar field for the time
3178     * value of this <code>Calendar</code>
3179     * @see #getMinimum(int)
3180     * @see #getMaximum(int)
3181     * @see #getGreatestMinimum(int)
3182     * @see #getLeastMaximum(int)
3183     * @see #getActualMaximum(int)
3184     * @since 1.2
3185     */
3186    public int getActualMinimum(int field) {
3187        int fieldValue = getGreatestMinimum(field);
3188        int endValue = getMinimum(field);
3189
3190        // if we know that the minimum value is always the same, just return it
3191        if (fieldValue == endValue) {
3192            return fieldValue;
3193        }
3194
3195        // clone the calendar so we don't mess with the real one, and set it to
3196        // accept anything for the field values
3197        Calendar work = (Calendar)this.clone();
3198        work.setLenient(true);
3199
3200        // now try each value from getLeastMaximum() to getMaximum() one by one until
3201        // we get a value that normalizes to another value.  The last value that
3202        // normalizes to itself is the actual minimum for the current date
3203        int result = fieldValue;
3204
3205        do {
3206            work.set(field, fieldValue);
3207            if (work.get(field) != fieldValue) {
3208                break;
3209            } else {
3210                result = fieldValue;
3211                fieldValue--;
3212            }
3213        } while (fieldValue >= endValue);
3214
3215        return result;
3216    }
3217
3218    /**
3219     * Returns the maximum value that the specified calendar field
3220     * could have, given the time value of this
3221     * <code>Calendar</code>. For example, the actual maximum value of
3222     * the <code>MONTH</code> field is 12 in some years, and 13 in
3223     * other years in the Hebrew calendar system.
3224     *
3225     * <p>The default implementation of this method uses an iterative
3226     * algorithm to determine the actual maximum value for the
3227     * calendar field. Subclasses should, if possible, override this
3228     * with a more efficient implementation.
3229     *
3230     * @param field the calendar field
3231     * @return the maximum of the given calendar field for the time
3232     * value of this <code>Calendar</code>
3233     * @see #getMinimum(int)
3234     * @see #getMaximum(int)
3235     * @see #getGreatestMinimum(int)
3236     * @see #getLeastMaximum(int)
3237     * @see #getActualMinimum(int)
3238     * @since 1.2
3239     */
3240    public int getActualMaximum(int field) {
3241        int fieldValue = getLeastMaximum(field);
3242        int endValue = getMaximum(field);
3243
3244        // if we know that the maximum value is always the same, just return it.
3245        if (fieldValue == endValue) {
3246            return fieldValue;
3247        }
3248
3249        // clone the calendar so we don't mess with the real one, and set it to
3250        // accept anything for the field values.
3251        Calendar work = (Calendar)this.clone();
3252        work.setLenient(true);
3253
3254        // if we're counting weeks, set the day of the week to Sunday.  We know the
3255        // last week of a month or year will contain the first day of the week.
3256        if (field == WEEK_OF_YEAR || field == WEEK_OF_MONTH) {
3257            work.set(DAY_OF_WEEK, firstDayOfWeek);
3258        }
3259
3260        // now try each value from getLeastMaximum() to getMaximum() one by one until
3261        // we get a value that normalizes to another value.  The last value that
3262        // normalizes to itself is the actual maximum for the current date
3263        int result = fieldValue;
3264
3265        do {
3266            work.set(field, fieldValue);
3267            if (work.get(field) != fieldValue) {
3268                break;
3269            } else {
3270                result = fieldValue;
3271                fieldValue++;
3272            }
3273        } while (fieldValue <= endValue);
3274
3275        return result;
3276    }
3277
3278    /**
3279     * Creates and returns a copy of this object.
3280     *
3281     * @return a copy of this object.
3282     */
3283    @Override
3284    public Object clone()
3285    {
3286        try {
3287            Calendar other = (Calendar) super.clone();
3288
3289            other.fields = new int[FIELD_COUNT];
3290            other.isSet = new boolean[FIELD_COUNT];
3291            other.stamp = new int[FIELD_COUNT];
3292            for (int i = 0; i < FIELD_COUNT; i++) {
3293                other.fields[i] = fields[i];
3294                other.stamp[i] = stamp[i];
3295                other.isSet[i] = isSet[i];
3296            }
3297            other.zone = (TimeZone) zone.clone();
3298            return other;
3299        }
3300        catch (CloneNotSupportedException e) {
3301            // this shouldn't happen, since we are Cloneable
3302            throw new InternalError(e);
3303        }
3304    }
3305
3306    private static final String[] FIELD_NAME = {
3307        "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH",
3308        "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR",
3309        "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET",
3310        "DST_OFFSET"
3311    };
3312
3313    /**
3314     * Returns the name of the specified calendar field.
3315     *
3316     * @param field the calendar field
3317     * @return the calendar field name
3318     * @exception IndexOutOfBoundsException if <code>field</code> is negative,
3319     * equal to or greater than {@code FIELD_COUNT}.
3320     */
3321    static String getFieldName(int field) {
3322        return FIELD_NAME[field];
3323    }
3324
3325    /**
3326     * Return a string representation of this calendar. This method
3327     * is intended to be used only for debugging purposes, and the
3328     * format of the returned string may vary between implementations.
3329     * The returned string may be empty but may not be <code>null</code>.
3330     *
3331     * @return  a string representation of this calendar.
3332     */
3333    @Override
3334    public String toString() {
3335        // NOTE: BuddhistCalendar.toString() interprets the string
3336        // produced by this method so that the Gregorian year number
3337        // is substituted by its B.E. year value. It relies on
3338        // "...,YEAR=<year>,..." or "...,YEAR=?,...".
3339        StringBuilder buffer = new StringBuilder(800);
3340        buffer.append(getClass().getName()).append('[');
3341        appendValue(buffer, "time", isTimeSet, time);
3342        buffer.append(",areFieldsSet=").append(areFieldsSet);
3343        buffer.append(",areAllFieldsSet=").append(areAllFieldsSet);
3344        buffer.append(",lenient=").append(lenient);
3345        buffer.append(",zone=").append(zone);
3346        appendValue(buffer, ",firstDayOfWeek", true, (long) firstDayOfWeek);
3347        appendValue(buffer, ",minimalDaysInFirstWeek", true, (long) minimalDaysInFirstWeek);
3348        for (int i = 0; i < FIELD_COUNT; ++i) {
3349            buffer.append(',');
3350            appendValue(buffer, FIELD_NAME[i], isSet(i), (long) fields[i]);
3351        }
3352        buffer.append(']');
3353        return buffer.toString();
3354    }
3355
3356    // =======================privates===============================
3357
3358    private static void appendValue(StringBuilder sb, String item, boolean valid, long value) {
3359        sb.append(item).append('=');
3360        if (valid) {
3361            sb.append(value);
3362        } else {
3363            sb.append('?');
3364        }
3365    }
3366
3367    /**
3368     * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.
3369     * They are used to figure out the week count for a specific date for
3370     * a given locale. These must be set when a Calendar is constructed.
3371     * @param desiredLocale the given locale.
3372     */
3373    private void setWeekCountData(Locale desiredLocale)
3374    {
3375        /* try to get the Locale data from the cache */
3376        int[] data = cachedLocaleData.get(desiredLocale);
3377        if (data == null) {  /* cache miss */
3378            data = new int[2];
3379            data[0] = CalendarDataUtility.retrieveFirstDayOfWeek(desiredLocale);
3380            data[1] = CalendarDataUtility.retrieveMinimalDaysInFirstWeek(desiredLocale);
3381            cachedLocaleData.putIfAbsent(desiredLocale, data);
3382        }
3383        firstDayOfWeek = data[0];
3384        minimalDaysInFirstWeek = data[1];
3385    }
3386
3387    /**
3388     * Recomputes the time and updates the status fields isTimeSet
3389     * and areFieldsSet.  Callers should check isTimeSet and only
3390     * call this method if isTimeSet is false.
3391     */
3392    private void updateTime() {
3393        computeTime();
3394        // The areFieldsSet and areAllFieldsSet values are no longer
3395        // controlled here (as of 1.5).
3396        isTimeSet = true;
3397    }
3398
3399    private int compareTo(long t) {
3400        long thisTime = getMillisOf(this);
3401        return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
3402    }
3403
3404    private static long getMillisOf(Calendar calendar) {
3405        if (calendar.isTimeSet) {
3406            return calendar.time;
3407        }
3408        Calendar cal = (Calendar) calendar.clone();
3409        cal.setLenient(true);
3410        return cal.getTimeInMillis();
3411    }
3412
3413    /**
3414     * Adjusts the stamp[] values before nextStamp overflow. nextStamp
3415     * is set to the next stamp value upon the return.
3416     */
3417    private void adjustStamp() {
3418        int max = MINIMUM_USER_STAMP;
3419        int newStamp = MINIMUM_USER_STAMP;
3420
3421        for (;;) {
3422            int min = Integer.MAX_VALUE;
3423            for (int v : stamp) {
3424                if (v >= newStamp && min > v) {
3425                    min = v;
3426                }
3427                if (max < v) {
3428                    max = v;
3429                }
3430            }
3431            if (max != min && min == Integer.MAX_VALUE) {
3432                break;
3433            }
3434            for (int i = 0; i < stamp.length; i++) {
3435                if (stamp[i] == min) {
3436                    stamp[i] = newStamp;
3437                }
3438            }
3439            newStamp++;
3440            if (min == max) {
3441                break;
3442            }
3443        }
3444        nextStamp = newStamp;
3445    }
3446
3447    /**
3448     * Sets the WEEK_OF_MONTH and WEEK_OF_YEAR fields to new values with the
3449     * new parameter value if they have been calculated internally.
3450     */
3451    private void invalidateWeekFields()
3452    {
3453        if (stamp[WEEK_OF_MONTH] != COMPUTED &&
3454            stamp[WEEK_OF_YEAR] != COMPUTED) {
3455            return;
3456        }
3457
3458        // We have to check the new values of these fields after changing
3459        // firstDayOfWeek and/or minimalDaysInFirstWeek. If the field values
3460        // have been changed, then set the new values. (4822110)
3461        Calendar cal = (Calendar) clone();
3462        cal.setLenient(true);
3463        cal.clear(WEEK_OF_MONTH);
3464        cal.clear(WEEK_OF_YEAR);
3465
3466        if (stamp[WEEK_OF_MONTH] == COMPUTED) {
3467            int weekOfMonth = cal.get(WEEK_OF_MONTH);
3468            if (fields[WEEK_OF_MONTH] != weekOfMonth) {
3469                fields[WEEK_OF_MONTH] = weekOfMonth;
3470            }
3471        }
3472
3473        if (stamp[WEEK_OF_YEAR] == COMPUTED) {
3474            int weekOfYear = cal.get(WEEK_OF_YEAR);
3475            if (fields[WEEK_OF_YEAR] != weekOfYear) {
3476                fields[WEEK_OF_YEAR] = weekOfYear;
3477            }
3478        }
3479    }
3480
3481    /**
3482     * Save the state of this object to a stream (i.e., serialize it).
3483     *
3484     * Ideally, <code>Calendar</code> would only write out its state data and
3485     * the current time, and not write any field data out, such as
3486     * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>,
3487     * and <code>isSet[]</code>.  <code>nextStamp</code> also should not be part
3488     * of the persistent state. Unfortunately, this didn't happen before JDK 1.1
3489     * shipped. To be compatible with JDK 1.1, we will always have to write out
3490     * the field values and state flags.  However, <code>nextStamp</code> can be
3491     * removed from the serialization stream; this will probably happen in the
3492     * near future.
3493     */
3494    private synchronized void writeObject(ObjectOutputStream stream)
3495         throws IOException
3496    {
3497        // Try to compute the time correctly, for the future (stream
3498        // version 2) in which we don't write out fields[] or isSet[].
3499        if (!isTimeSet) {
3500            try {
3501                updateTime();
3502            }
3503            catch (IllegalArgumentException e) {}
3504        }
3505
3506        // If this Calendar has a ZoneInfo, save it and set a
3507        // SimpleTimeZone equivalent (as a single DST schedule) for
3508        // backward compatibility.
3509        TimeZone savedZone = null;
3510        if (zone instanceof ZoneInfo) {
3511            SimpleTimeZone stz = ((ZoneInfo)zone).getLastRuleInstance();
3512            if (stz == null) {
3513                stz = new SimpleTimeZone(zone.getRawOffset(), zone.getID());
3514            }
3515            savedZone = zone;
3516            zone = stz;
3517        }
3518
3519        // Write out the 1.1 FCS object.
3520        stream.defaultWriteObject();
3521
3522        // Write out the ZoneInfo object
3523        // 4802409: we write out even if it is null, a temporary workaround
3524        // the real fix for bug 4844924 in corba-iiop
3525        stream.writeObject(savedZone);
3526        if (savedZone != null) {
3527            zone = savedZone;
3528        }
3529    }
3530
3531    private static class CalendarAccessControlContext {
3532        private static final AccessControlContext INSTANCE;
3533        static {
3534            RuntimePermission perm = new RuntimePermission("accessClassInPackage.sun.util.calendar");
3535            PermissionCollection perms = perm.newPermissionCollection();
3536            perms.add(perm);
3537            INSTANCE = new AccessControlContext(new ProtectionDomain[] {
3538                                                    new ProtectionDomain(null, perms)
3539                                                });
3540        }
3541        private CalendarAccessControlContext() {
3542        }
3543    }
3544
3545    /**
3546     * Reconstitutes this object from a stream (i.e., deserialize it).
3547     */
3548    private void readObject(ObjectInputStream stream)
3549         throws IOException, ClassNotFoundException
3550    {
3551        final ObjectInputStream input = stream;
3552        input.defaultReadObject();
3553
3554        stamp = new int[FIELD_COUNT];
3555
3556        // Starting with version 2 (not implemented yet), we expect that
3557        // fields[], isSet[], isTimeSet, and areFieldsSet may not be
3558        // streamed out anymore.  We expect 'time' to be correct.
3559        if (serialVersionOnStream >= 2)
3560        {
3561            isTimeSet = true;
3562            if (fields == null) {
3563                fields = new int[FIELD_COUNT];
3564            }
3565            if (isSet == null) {
3566                isSet = new boolean[FIELD_COUNT];
3567            }
3568        }
3569        else if (serialVersionOnStream >= 0)
3570        {
3571            for (int i=0; i<FIELD_COUNT; ++i) {
3572                stamp[i] = isSet[i] ? COMPUTED : UNSET;
3573            }
3574        }
3575
3576        serialVersionOnStream = currentSerialVersion;
3577
3578        // If there's a ZoneInfo object, use it for zone.
3579        ZoneInfo zi = null;
3580        try {
3581            zi = AccessController.doPrivileged(
3582                    new PrivilegedExceptionAction<>() {
3583                        @Override
3584                        public ZoneInfo run() throws Exception {
3585                            return (ZoneInfo) input.readObject();
3586                        }
3587                    },
3588                    CalendarAccessControlContext.INSTANCE);
3589        } catch (PrivilegedActionException pae) {
3590            Exception e = pae.getException();
3591            if (!(e instanceof OptionalDataException)) {
3592                if (e instanceof RuntimeException) {
3593                    throw (RuntimeException) e;
3594                } else if (e instanceof IOException) {
3595                    throw (IOException) e;
3596                } else if (e instanceof ClassNotFoundException) {
3597                    throw (ClassNotFoundException) e;
3598                }
3599                throw new RuntimeException(e);
3600            }
3601        }
3602        if (zi != null) {
3603            zone = zi;
3604        }
3605
3606        // If the deserialized object has a SimpleTimeZone, try to
3607        // replace it with a ZoneInfo equivalent (as of 1.4) in order
3608        // to be compatible with the SimpleTimeZone-based
3609        // implementation as much as possible.
3610        if (zone instanceof SimpleTimeZone) {
3611            String id = zone.getID();
3612            TimeZone tz = TimeZone.getTimeZone(id);
3613            if (tz != null && tz.hasSameRules(zone) && tz.getID().equals(id)) {
3614                zone = tz;
3615            }
3616        }
3617    }
3618
3619    /**
3620     * Converts this object to an {@link Instant}.
3621     * <p>
3622     * The conversion creates an {@code Instant} that represents the
3623     * same point on the time-line as this {@code Calendar}.
3624     *
3625     * @return the instant representing the same point on the time-line
3626     * @since 1.8
3627     */
3628    public final Instant toInstant() {
3629        return Instant.ofEpochMilli(getTimeInMillis());
3630    }
3631}
3632