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