Calendar.java revision dc4414b90a99639a0701c321472e29200b7ae0a0
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        // Android-changed: Android has traditionally treated ALL_STYLES as SHORT, even though
2038        // it's not documented to be a valid value for style.
2039        if (style == ALL_STYLES) {
2040            style = SHORT;
2041        }
2042        if (!checkDisplayNameParams(field, style, SHORT, NARROW_FORMAT, locale,
2043                            ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
2044            return null;
2045        }
2046
2047        String calendarType = getCalendarType();
2048        int fieldValue = get(field);
2049        // the standalone and narrow styles are supported only through CalendarDataProviders.
2050        if (isStandaloneStyle(style) || isNarrowFormatStyle(style)) {
2051            String val = CalendarDataUtility.retrieveFieldValueName(calendarType,
2052                                                                    field, fieldValue,
2053                                                                    style, locale);
2054            // Perform fallback here to follow the CLDR rules
2055            if (val == null) {
2056                if (isNarrowFormatStyle(style)) {
2057                    val = CalendarDataUtility.retrieveFieldValueName(calendarType,
2058                                                                     field, fieldValue,
2059                                                                     toStandaloneStyle(style),
2060                                                                     locale);
2061                } else if (isStandaloneStyle(style)) {
2062                    val = CalendarDataUtility.retrieveFieldValueName(calendarType,
2063                                                                     field, fieldValue,
2064                                                                     getBaseStyle(style),
2065                                                                     locale);
2066                }
2067            }
2068            return val;
2069        }
2070
2071        DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
2072        String[] strings = getFieldStrings(field, style, symbols);
2073        if (strings != null) {
2074            if (fieldValue < strings.length) {
2075                return strings[fieldValue];
2076            }
2077        }
2078        return null;
2079    }
2080
2081    /**
2082     * Returns a {@code Map} containing all names of the calendar
2083     * {@code field} in the given {@code style} and
2084     * {@code locale} and their corresponding field values. For
2085     * example, if this {@code Calendar} is a {@link
2086     * GregorianCalendar}, the returned map would contain "Jan" to
2087     * {@link #JANUARY}, "Feb" to {@link #FEBRUARY}, and so on, in the
2088     * {@linkplain #SHORT short} style in an English locale.
2089     *
2090     * <p>Narrow names may not be unique due to use of single characters,
2091     * such as "S" for Sunday and Saturday. In that case narrow names are not
2092     * included in the returned {@code Map}.
2093     *
2094     * <p>The values of other calendar fields may be taken into
2095     * account to determine a set of display names. For example, if
2096     * this {@code Calendar} is a lunisolar calendar system and
2097     * the year value given by the {@link #YEAR} field has a leap
2098     * month, this method would return month names containing the leap
2099     * month name, and month names are mapped to their values specific
2100     * for the year.
2101     *
2102     * <p>The default implementation supports display names contained in
2103     * a {@link DateFormatSymbols}. For example, if {@code field}
2104     * is {@link #MONTH} and {@code style} is {@link
2105     * #ALL_STYLES}, this method returns a {@code Map} containing
2106     * all strings returned by {@link DateFormatSymbols#getShortMonths()}
2107     * and {@link DateFormatSymbols#getMonths()}.
2108     *
2109     * @param field
2110     *        the calendar field for which the display names are returned
2111     * @param style
2112     *        the style applied to the string representation; one of {@link
2113     *        #SHORT_FORMAT} ({@link #SHORT}), {@link #SHORT_STANDALONE},
2114     *        {@link #LONG_FORMAT} ({@link #LONG}), {@link #LONG_STANDALONE},
2115     *        {@link #NARROW_FORMAT}, or {@link #NARROW_STANDALONE}
2116     * @param locale
2117     *        the locale for the display names
2118     * @return a {@code Map} containing all display names in
2119     *        {@code style} and {@code locale} and their
2120     *        field values, or {@code null} if no display names
2121     *        are defined for {@code field}
2122     * @exception IllegalArgumentException
2123     *        if {@code field} or {@code style} is invalid,
2124     *        or if this {@code Calendar} is non-lenient and any
2125     *        of the calendar fields have invalid values
2126     * @exception NullPointerException
2127     *        if {@code locale} is null
2128     * @since 1.6
2129     */
2130    public Map<String, Integer> getDisplayNames(int field, int style, Locale locale) {
2131        if (!checkDisplayNameParams(field, style, ALL_STYLES, NARROW_FORMAT, locale,
2132                                    ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
2133            return null;
2134        }
2135        complete();
2136
2137        String calendarType = getCalendarType();
2138        if (style == ALL_STYLES || isStandaloneStyle(style) || isNarrowFormatStyle(style)) {
2139            Map<String, Integer> map;
2140            map = CalendarDataUtility.retrieveFieldValueNames(calendarType, field, style, locale);
2141
2142            // Perform fallback here to follow the CLDR rules
2143            if (map == null) {
2144                if (isNarrowFormatStyle(style)) {
2145                    map = CalendarDataUtility.retrieveFieldValueNames(calendarType, field,
2146                                                                      toStandaloneStyle(style), locale);
2147                } else if (style != ALL_STYLES) {
2148                    map = CalendarDataUtility.retrieveFieldValueNames(calendarType, field,
2149                                                                      getBaseStyle(style), locale);
2150                }
2151            }
2152            return map;
2153        }
2154
2155        // SHORT or LONG
2156        return getDisplayNamesImpl(field, style, locale);
2157    }
2158
2159    private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) {
2160        DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
2161        String[] strings = getFieldStrings(field, style, symbols);
2162        if (strings != null) {
2163            Map<String,Integer> names = new HashMap<>();
2164            for (int i = 0; i < strings.length; i++) {
2165                if (strings[i].length() == 0) {
2166                    continue;
2167                }
2168                names.put(strings[i], i);
2169            }
2170            return names;
2171        }
2172        return null;
2173    }
2174
2175    boolean checkDisplayNameParams(int field, int style, int minStyle, int maxStyle,
2176                                   Locale locale, int fieldMask) {
2177        int baseStyle = getBaseStyle(style); // Ignore the standalone mask
2178        if (field < 0 || field >= fields.length ||
2179            baseStyle < minStyle || baseStyle > maxStyle) {
2180            throw new IllegalArgumentException();
2181        }
2182        // Android-changed: 3 is not a valid base style (1, 2 and 4 are, though), throw if used.
2183        if (baseStyle == 3) {
2184            throw new IllegalArgumentException();
2185        }
2186        if (locale == null) {
2187            throw new NullPointerException();
2188        }
2189        return isFieldSet(fieldMask, field);
2190    }
2191
2192    private String[] getFieldStrings(int field, int style, DateFormatSymbols symbols) {
2193        int baseStyle = getBaseStyle(style); // ignore the standalone mask
2194
2195        // DateFormatSymbols doesn't support any narrow names.
2196        if (baseStyle == NARROW_FORMAT) {
2197            return null;
2198        }
2199
2200        String[] strings = null;
2201        switch (field) {
2202        case ERA:
2203            strings = symbols.getEras();
2204            break;
2205
2206        case MONTH:
2207            strings = (baseStyle == LONG) ? symbols.getMonths() : symbols.getShortMonths();
2208            break;
2209
2210        case DAY_OF_WEEK:
2211            strings = (baseStyle == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays();
2212            break;
2213
2214        case AM_PM:
2215            strings = symbols.getAmPmStrings();
2216            break;
2217        }
2218        return strings;
2219    }
2220
2221    /**
2222     * Fills in any unset fields in the calendar fields. First, the {@link
2223     * #computeTime()} method is called if the time value (millisecond offset
2224     * from the <a href="#Epoch">Epoch</a>) has not been calculated from
2225     * calendar field values. Then, the {@link #computeFields()} method is
2226     * called to calculate all calendar field values.
2227     */
2228    protected void complete()
2229    {
2230        if (!isTimeSet) {
2231            updateTime();
2232        }
2233        if (!areFieldsSet || !areAllFieldsSet) {
2234            computeFields(); // fills in unset fields
2235            areAllFieldsSet = areFieldsSet = true;
2236        }
2237    }
2238
2239    /**
2240     * Returns whether the value of the specified calendar field has been set
2241     * externally by calling one of the setter methods rather than by the
2242     * internal time calculation.
2243     *
2244     * @return <code>true</code> if the field has been set externally,
2245     * <code>false</code> otherwise.
2246     * @exception IndexOutOfBoundsException if the specified
2247     *                <code>field</code> is out of range
2248     *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
2249     * @see #selectFields()
2250     * @see #setFieldsComputed(int)
2251     */
2252    final boolean isExternallySet(int field) {
2253        return stamp[field] >= MINIMUM_USER_STAMP;
2254    }
2255
2256    /**
2257     * Returns a field mask (bit mask) indicating all calendar fields that
2258     * have the state of externally or internally set.
2259     *
2260     * @return a bit mask indicating set state fields
2261     */
2262    final int getSetStateFields() {
2263        int mask = 0;
2264        for (int i = 0; i < fields.length; i++) {
2265            if (stamp[i] != UNSET) {
2266                mask |= 1 << i;
2267            }
2268        }
2269        return mask;
2270    }
2271
2272    /**
2273     * Sets the state of the specified calendar fields to
2274     * <em>computed</em>. This state means that the specified calendar fields
2275     * have valid values that have been set by internal time calculation
2276     * rather than by calling one of the setter methods.
2277     *
2278     * @param fieldMask the field to be marked as computed.
2279     * @exception IndexOutOfBoundsException if the specified
2280     *                <code>field</code> is out of range
2281     *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
2282     * @see #isExternallySet(int)
2283     * @see #selectFields()
2284     */
2285    final void setFieldsComputed(int fieldMask) {
2286        if (fieldMask == ALL_FIELDS) {
2287            for (int i = 0; i < fields.length; i++) {
2288                stamp[i] = COMPUTED;
2289                isSet[i] = true;
2290            }
2291            areFieldsSet = areAllFieldsSet = true;
2292        } else {
2293            for (int i = 0; i < fields.length; i++) {
2294                if ((fieldMask & 1) == 1) {
2295                    stamp[i] = COMPUTED;
2296                    isSet[i] = true;
2297                } else {
2298                    if (areAllFieldsSet && !isSet[i]) {
2299                        areAllFieldsSet = false;
2300                    }
2301                }
2302                fieldMask >>>= 1;
2303            }
2304        }
2305    }
2306
2307    /**
2308     * Sets the state of the calendar fields that are <em>not</em> specified
2309     * by <code>fieldMask</code> to <em>unset</em>. If <code>fieldMask</code>
2310     * specifies all the calendar fields, then the state of this
2311     * <code>Calendar</code> becomes that all the calendar fields are in sync
2312     * with the time value (millisecond offset from the Epoch).
2313     *
2314     * @param fieldMask the field mask indicating which calendar fields are in
2315     * sync with the time value.
2316     * @exception IndexOutOfBoundsException if the specified
2317     *                <code>field</code> is out of range
2318     *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
2319     * @see #isExternallySet(int)
2320     * @see #selectFields()
2321     */
2322    final void setFieldsNormalized(int fieldMask) {
2323        if (fieldMask != ALL_FIELDS) {
2324            for (int i = 0; i < fields.length; i++) {
2325                if ((fieldMask & 1) == 0) {
2326                    stamp[i] = fields[i] = 0; // UNSET == 0
2327                    isSet[i] = false;
2328                }
2329                fieldMask >>= 1;
2330            }
2331        }
2332
2333        // Some or all of the fields are in sync with the
2334        // milliseconds, but the stamp values are not normalized yet.
2335        areFieldsSet = true;
2336        areAllFieldsSet = false;
2337    }
2338
2339    /**
2340     * Returns whether the calendar fields are partially in sync with the time
2341     * value or fully in sync but not stamp values are not normalized yet.
2342     */
2343    final boolean isPartiallyNormalized() {
2344        return areFieldsSet && !areAllFieldsSet;
2345    }
2346
2347    /**
2348     * Returns whether the calendar fields are fully in sync with the time
2349     * value.
2350     */
2351    final boolean isFullyNormalized() {
2352        return areFieldsSet && areAllFieldsSet;
2353    }
2354
2355    /**
2356     * Marks this Calendar as not sync'd.
2357     */
2358    final void setUnnormalized() {
2359        areFieldsSet = areAllFieldsSet = false;
2360    }
2361
2362    /**
2363     * Returns whether the specified <code>field</code> is on in the
2364     * <code>fieldMask</code>.
2365     */
2366    static boolean isFieldSet(int fieldMask, int field) {
2367        return (fieldMask & (1 << field)) != 0;
2368    }
2369
2370    /**
2371     * Returns a field mask indicating which calendar field values
2372     * to be used to calculate the time value. The calendar fields are
2373     * returned as a bit mask, each bit of which corresponds to a field, i.e.,
2374     * the mask value of <code>field</code> is <code>(1 &lt;&lt;
2375     * field)</code>. For example, 0x26 represents the <code>YEAR</code>,
2376     * <code>MONTH</code>, and <code>DAY_OF_MONTH</code> fields (i.e., 0x26 is
2377     * equal to
2378     * <code>(1&lt;&lt;YEAR)|(1&lt;&lt;MONTH)|(1&lt;&lt;DAY_OF_MONTH))</code>.
2379     *
2380     * <p>This method supports the calendar fields resolution as described in
2381     * the class description. If the bit mask for a given field is on and its
2382     * field has not been set (i.e., <code>isSet(field)</code> is
2383     * <code>false</code>), then the default value of the field has to be
2384     * used, which case means that the field has been selected because the
2385     * selected combination involves the field.
2386     *
2387     * @return a bit mask of selected fields
2388     * @see #isExternallySet(int)
2389     */
2390    final int selectFields() {
2391        // This implementation has been taken from the GregorianCalendar class.
2392
2393        // The YEAR field must always be used regardless of its SET
2394        // state because YEAR is a mandatory field to determine the date
2395        // and the default value (EPOCH_YEAR) may change through the
2396        // normalization process.
2397        int fieldMask = YEAR_MASK;
2398
2399        if (stamp[ERA] != UNSET) {
2400            fieldMask |= ERA_MASK;
2401        }
2402        // Find the most recent group of fields specifying the day within
2403        // the year.  These may be any of the following combinations:
2404        //   MONTH + DAY_OF_MONTH
2405        //   MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
2406        //   MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
2407        //   DAY_OF_YEAR
2408        //   WEEK_OF_YEAR + DAY_OF_WEEK
2409        // We look for the most recent of the fields in each group to determine
2410        // the age of the group.  For groups involving a week-related field such
2411        // as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the
2412        // week-related field and the DAY_OF_WEEK must be set for the group as a
2413        // whole to be considered.  (See bug 4153860 - liu 7/24/98.)
2414        int dowStamp = stamp[DAY_OF_WEEK];
2415        int monthStamp = stamp[MONTH];
2416        int domStamp = stamp[DAY_OF_MONTH];
2417        int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp);
2418        int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
2419        int doyStamp = stamp[DAY_OF_YEAR];
2420        int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp);
2421
2422        int bestStamp = domStamp;
2423        if (womStamp > bestStamp) {
2424            bestStamp = womStamp;
2425        }
2426        if (dowimStamp > bestStamp) {
2427            bestStamp = dowimStamp;
2428        }
2429        if (doyStamp > bestStamp) {
2430            bestStamp = doyStamp;
2431        }
2432        if (woyStamp > bestStamp) {
2433            bestStamp = woyStamp;
2434        }
2435
2436        /* No complete combination exists.  Look for WEEK_OF_MONTH,
2437         * DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone.  Treat DAY_OF_WEEK alone
2438         * as DAY_OF_WEEK_IN_MONTH.
2439         */
2440        if (bestStamp == UNSET) {
2441            womStamp = stamp[WEEK_OF_MONTH];
2442            dowimStamp = Math.max(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
2443            woyStamp = stamp[WEEK_OF_YEAR];
2444            bestStamp = Math.max(Math.max(womStamp, dowimStamp), woyStamp);
2445
2446            /* Treat MONTH alone or no fields at all as DAY_OF_MONTH.  This may
2447             * result in bestStamp = domStamp = UNSET if no fields are set,
2448             * which indicates DAY_OF_MONTH.
2449             */
2450            if (bestStamp == UNSET) {
2451                bestStamp = domStamp = monthStamp;
2452            }
2453        }
2454
2455        if (bestStamp == domStamp ||
2456           (bestStamp == womStamp && stamp[WEEK_OF_MONTH] >= stamp[WEEK_OF_YEAR]) ||
2457           (bestStamp == dowimStamp && stamp[DAY_OF_WEEK_IN_MONTH] >= stamp[WEEK_OF_YEAR])) {
2458            fieldMask |= MONTH_MASK;
2459            if (bestStamp == domStamp) {
2460                fieldMask |= DAY_OF_MONTH_MASK;
2461            } else {
2462                assert (bestStamp == womStamp || bestStamp == dowimStamp);
2463                if (dowStamp != UNSET) {
2464                    fieldMask |= DAY_OF_WEEK_MASK;
2465                }
2466                if (womStamp == dowimStamp) {
2467                    // When they are equal, give the priority to
2468                    // WEEK_OF_MONTH for compatibility.
2469                    if (stamp[WEEK_OF_MONTH] >= stamp[DAY_OF_WEEK_IN_MONTH]) {
2470                        fieldMask |= WEEK_OF_MONTH_MASK;
2471                    } else {
2472                        fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
2473                    }
2474                } else {
2475                    if (bestStamp == womStamp) {
2476                        fieldMask |= WEEK_OF_MONTH_MASK;
2477                    } else {
2478                        assert (bestStamp == dowimStamp);
2479                        if (stamp[DAY_OF_WEEK_IN_MONTH] != UNSET) {
2480                            fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
2481                        }
2482                    }
2483                }
2484            }
2485        } else {
2486            assert (bestStamp == doyStamp || bestStamp == woyStamp ||
2487                    bestStamp == UNSET);
2488            if (bestStamp == doyStamp) {
2489                fieldMask |= DAY_OF_YEAR_MASK;
2490            } else {
2491                assert (bestStamp == woyStamp);
2492                if (dowStamp != UNSET) {
2493                    fieldMask |= DAY_OF_WEEK_MASK;
2494                }
2495                fieldMask |= WEEK_OF_YEAR_MASK;
2496            }
2497        }
2498
2499        // Find the best set of fields specifying the time of day.  There
2500        // are only two possibilities here; the HOUR_OF_DAY or the
2501        // AM_PM and the HOUR.
2502        int hourOfDayStamp = stamp[HOUR_OF_DAY];
2503        int hourStamp = aggregateStamp(stamp[HOUR], stamp[AM_PM]);
2504        bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
2505
2506        // if bestStamp is still UNSET, then take HOUR or AM_PM. (See 4846659)
2507        if (bestStamp == UNSET) {
2508            bestStamp = Math.max(stamp[HOUR], stamp[AM_PM]);
2509        }
2510
2511        // Hours
2512        if (bestStamp != UNSET) {
2513            if (bestStamp == hourOfDayStamp) {
2514                fieldMask |= HOUR_OF_DAY_MASK;
2515            } else {
2516                fieldMask |= HOUR_MASK;
2517                if (stamp[AM_PM] != UNSET) {
2518                    fieldMask |= AM_PM_MASK;
2519                }
2520            }
2521        }
2522        if (stamp[MINUTE] != UNSET) {
2523            fieldMask |= MINUTE_MASK;
2524        }
2525        if (stamp[SECOND] != UNSET) {
2526            fieldMask |= SECOND_MASK;
2527        }
2528        if (stamp[MILLISECOND] != UNSET) {
2529            fieldMask |= MILLISECOND_MASK;
2530        }
2531        if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) {
2532                fieldMask |= ZONE_OFFSET_MASK;
2533        }
2534        if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) {
2535            fieldMask |= DST_OFFSET_MASK;
2536        }
2537
2538        return fieldMask;
2539    }
2540
2541    int getBaseStyle(int style) {
2542        return style & ~STANDALONE_MASK;
2543    }
2544
2545    private int toStandaloneStyle(int style) {
2546        return style | STANDALONE_MASK;
2547    }
2548
2549    private boolean isStandaloneStyle(int style) {
2550        return (style & STANDALONE_MASK) != 0;
2551    }
2552
2553    private boolean isNarrowStyle(int style) {
2554        return style == NARROW_FORMAT || style == NARROW_STANDALONE;
2555    }
2556
2557    private boolean isNarrowFormatStyle(int style) {
2558        return style == NARROW_FORMAT;
2559    }
2560
2561    /**
2562     * Returns the pseudo-time-stamp for two fields, given their
2563     * individual pseudo-time-stamps.  If either of the fields
2564     * is unset, then the aggregate is unset.  Otherwise, the
2565     * aggregate is the later of the two stamps.
2566     */
2567    private static int aggregateStamp(int stamp_a, int stamp_b) {
2568        if (stamp_a == UNSET || stamp_b == UNSET) {
2569            return UNSET;
2570        }
2571        return (stamp_a > stamp_b) ? stamp_a : stamp_b;
2572    }
2573
2574    /**
2575     * Returns an unmodifiable {@code Set} containing all calendar types
2576     * supported by {@code Calendar} in the runtime environment. The available
2577     * calendar types can be used for the <a
2578     * href="Locale.html#def_locale_extension">Unicode locale extensions</a>.
2579     * The {@code Set} returned contains at least {@code "gregory"}. The
2580     * calendar types don't include aliases, such as {@code "gregorian"} for
2581     * {@code "gregory"}.
2582     *
2583     * @return an unmodifiable {@code Set} containing all available calendar types
2584     * @since 1.8
2585     * @see #getCalendarType()
2586     * @see Calendar.Builder#setCalendarType(String)
2587     * @see Locale#getUnicodeLocaleType(String)
2588     */
2589    public static Set<String> getAvailableCalendarTypes() {
2590        return AvailableCalendarTypes.SET;
2591    }
2592
2593    private static class AvailableCalendarTypes {
2594        private static final Set<String> SET;
2595        static {
2596            Set<String> set = new HashSet<>(3);
2597            set.add("gregory");
2598            SET = Collections.unmodifiableSet(set);
2599        }
2600        private AvailableCalendarTypes() {
2601        }
2602    }
2603
2604    /**
2605     * Returns the calendar type of this {@code Calendar}. Calendar types are
2606     * defined by the <em>Unicode Locale Data Markup Language (LDML)</em>
2607     * specification.
2608     *
2609     * <p>The default implementation of this method returns the class name of
2610     * this {@code Calendar} instance. Any subclasses that implement
2611     * LDML-defined calendar systems should override this method to return
2612     * appropriate calendar types.
2613     *
2614     * @return the LDML-defined calendar type or the class name of this
2615     *         {@code Calendar} instance
2616     * @since 1.8
2617     * @see <a href="Locale.html#def_extensions">Locale extensions</a>
2618     * @see Locale.Builder#setLocale(Locale)
2619     * @see Locale.Builder#setUnicodeLocaleKeyword(String, String)
2620     */
2621    public String getCalendarType() {
2622        return this.getClass().getName();
2623    }
2624
2625    /**
2626     * Compares this <code>Calendar</code> to the specified
2627     * <code>Object</code>.  The result is <code>true</code> if and only if
2628     * the argument is a <code>Calendar</code> object of the same calendar
2629     * system that represents the same time value (millisecond offset from the
2630     * <a href="#Epoch">Epoch</a>) under the same
2631     * <code>Calendar</code> parameters as this object.
2632     *
2633     * <p>The <code>Calendar</code> parameters are the values represented
2634     * by the <code>isLenient</code>, <code>getFirstDayOfWeek</code>,
2635     * <code>getMinimalDaysInFirstWeek</code> and <code>getTimeZone</code>
2636     * methods. If there is any difference in those parameters
2637     * between the two <code>Calendar</code>s, this method returns
2638     * <code>false</code>.
2639     *
2640     * <p>Use the {@link #compareTo(Calendar) compareTo} method to
2641     * compare only the time values.
2642     *
2643     * @param obj the object to compare with.
2644     * @return <code>true</code> if this object is equal to <code>obj</code>;
2645     * <code>false</code> otherwise.
2646     */
2647    @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
2648    @Override
2649    public boolean equals(Object obj) {
2650        if (this == obj) {
2651            return true;
2652        }
2653        try {
2654            Calendar that = (Calendar)obj;
2655            return compareTo(getMillisOf(that)) == 0 &&
2656                lenient == that.lenient &&
2657                firstDayOfWeek == that.firstDayOfWeek &&
2658                minimalDaysInFirstWeek == that.minimalDaysInFirstWeek &&
2659                zone.equals(that.zone);
2660        } catch (Exception e) {
2661            // Note: GregorianCalendar.computeTime throws
2662            // IllegalArgumentException if the ERA value is invalid
2663            // even it's in lenient mode.
2664        }
2665        return false;
2666    }
2667
2668    /**
2669     * Returns a hash code for this calendar.
2670     *
2671     * @return a hash code value for this object.
2672     * @since 1.2
2673     */
2674    @Override
2675    public int hashCode() {
2676        // 'otheritems' represents the hash code for the previous versions.
2677        int otheritems = (lenient ? 1 : 0)
2678            | (firstDayOfWeek << 1)
2679            | (minimalDaysInFirstWeek << 4)
2680            | (zone.hashCode() << 7);
2681        long t = getMillisOf(this);
2682        return (int) t ^ (int)(t >> 32) ^ otheritems;
2683    }
2684
2685    /**
2686     * Returns whether this <code>Calendar</code> represents a time
2687     * before the time represented by the specified
2688     * <code>Object</code>. This method is equivalent to:
2689     * <pre>{@code
2690     *         compareTo(when) < 0
2691     * }</pre>
2692     * if and only if <code>when</code> is a <code>Calendar</code>
2693     * instance. Otherwise, the method returns <code>false</code>.
2694     *
2695     * @param when the <code>Object</code> to be compared
2696     * @return <code>true</code> if the time of this
2697     * <code>Calendar</code> is before the time represented by
2698     * <code>when</code>; <code>false</code> otherwise.
2699     * @see     #compareTo(Calendar)
2700     */
2701    public boolean before(Object when) {
2702        return when instanceof Calendar
2703            && compareTo((Calendar)when) < 0;
2704    }
2705
2706    /**
2707     * Returns whether this <code>Calendar</code> represents a time
2708     * after the time represented by the specified
2709     * <code>Object</code>. This method is equivalent to:
2710     * <pre>{@code
2711     *         compareTo(when) > 0
2712     * }</pre>
2713     * if and only if <code>when</code> is a <code>Calendar</code>
2714     * instance. Otherwise, the method returns <code>false</code>.
2715     *
2716     * @param when the <code>Object</code> to be compared
2717     * @return <code>true</code> if the time of this <code>Calendar</code> is
2718     * after the time represented by <code>when</code>; <code>false</code>
2719     * otherwise.
2720     * @see     #compareTo(Calendar)
2721     */
2722    public boolean after(Object when) {
2723        return when instanceof Calendar
2724            && compareTo((Calendar)when) > 0;
2725    }
2726
2727    /**
2728     * Compares the time values (millisecond offsets from the <a
2729     * href="#Epoch">Epoch</a>) represented by two
2730     * <code>Calendar</code> objects.
2731     *
2732     * @param anotherCalendar the <code>Calendar</code> to be compared.
2733     * @return the value <code>0</code> if the time represented by the argument
2734     * is equal to the time represented by this <code>Calendar</code>; a value
2735     * less than <code>0</code> if the time of this <code>Calendar</code> is
2736     * before the time represented by the argument; and a value greater than
2737     * <code>0</code> if the time of this <code>Calendar</code> is after the
2738     * time represented by the argument.
2739     * @exception NullPointerException if the specified <code>Calendar</code> is
2740     *            <code>null</code>.
2741     * @exception IllegalArgumentException if the time value of the
2742     * specified <code>Calendar</code> object can't be obtained due to
2743     * any invalid calendar values.
2744     * @since   1.5
2745     */
2746    @Override
2747    public int compareTo(Calendar anotherCalendar) {
2748        return compareTo(getMillisOf(anotherCalendar));
2749    }
2750
2751    /**
2752     * Adds or subtracts the specified amount of time to the given calendar field,
2753     * based on the calendar's rules. For example, to subtract 5 days from
2754     * the current time of the calendar, you can achieve it by calling:
2755     * <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>.
2756     *
2757     * @param field the calendar field.
2758     * @param amount the amount of date or time to be added to the field.
2759     * @see #roll(int,int)
2760     * @see #set(int,int)
2761     */
2762    abstract public void add(int field, int amount);
2763
2764    /**
2765     * Adds or subtracts (up/down) a single unit of time on the given time
2766     * field without changing larger fields. For example, to roll the current
2767     * date up by one day, you can achieve it by calling:
2768     * <p>roll(Calendar.DATE, true).
2769     * When rolling on the year or Calendar.YEAR field, it will roll the year
2770     * value in the range between 1 and the value returned by calling
2771     * <code>getMaximum(Calendar.YEAR)</code>.
2772     * When rolling on the month or Calendar.MONTH field, other fields like
2773     * date might conflict and, need to be changed. For instance,
2774     * rolling the month on the date 01/31/96 will result in 02/29/96.
2775     * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will
2776     * roll the hour value in the range between 0 and 23, which is zero-based.
2777     *
2778     * @param field the time field.
2779     * @param up indicates if the value of the specified time field is to be
2780     * rolled up or rolled down. Use true if rolling up, false otherwise.
2781     * @see Calendar#add(int,int)
2782     * @see Calendar#set(int,int)
2783     */
2784    abstract public void roll(int field, boolean up);
2785
2786    /**
2787     * Adds the specified (signed) amount to the specified calendar field
2788     * without changing larger fields.  A negative amount means to roll
2789     * down.
2790     *
2791     * <p>NOTE:  This default implementation on <code>Calendar</code> just repeatedly calls the
2792     * version of {@link #roll(int,boolean) roll()} that rolls by one unit.  This may not
2793     * always do the right thing.  For example, if the <code>DAY_OF_MONTH</code> field is 31,
2794     * rolling through February will leave it set to 28.  The <code>GregorianCalendar</code>
2795     * version of this function takes care of this problem.  Other subclasses
2796     * should also provide overrides of this function that do the right thing.
2797     *
2798     * @param field the calendar field.
2799     * @param amount the signed amount to add to the calendar <code>field</code>.
2800     * @since 1.2
2801     * @see #roll(int,boolean)
2802     * @see #add(int,int)
2803     * @see #set(int,int)
2804     */
2805    public void roll(int field, int amount)
2806    {
2807        while (amount > 0) {
2808            roll(field, true);
2809            amount--;
2810        }
2811        while (amount < 0) {
2812            roll(field, false);
2813            amount++;
2814        }
2815    }
2816
2817    /**
2818     * Sets the time zone with the given time zone value.
2819     *
2820     * @param value the given time zone.
2821     */
2822    public void setTimeZone(TimeZone value)
2823    {
2824        zone = value;
2825        sharedZone = false;
2826        /* Recompute the fields from the time using the new zone.  This also
2827         * works if isTimeSet is false (after a call to set()).  In that case
2828         * the time will be computed from the fields using the new zone, then
2829         * the fields will get recomputed from that.  Consider the sequence of
2830         * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
2831         * Is cal set to 1 o'clock EST or 1 o'clock PST?  Answer: PST.  More
2832         * generally, a call to setTimeZone() affects calls to set() BEFORE AND
2833         * AFTER it up to the next call to complete().
2834         */
2835        areAllFieldsSet = areFieldsSet = false;
2836    }
2837
2838    /**
2839     * Gets the time zone.
2840     *
2841     * @return the time zone object associated with this calendar.
2842     */
2843    public TimeZone getTimeZone()
2844    {
2845        // If the TimeZone object is shared by other Calendar instances, then
2846        // create a clone.
2847        if (sharedZone) {
2848            zone = (TimeZone) zone.clone();
2849            sharedZone = false;
2850        }
2851        return zone;
2852    }
2853
2854    /**
2855     * Returns the time zone (without cloning).
2856     */
2857    TimeZone getZone() {
2858        return zone;
2859    }
2860
2861    /**
2862     * Sets the sharedZone flag to <code>shared</code>.
2863     */
2864    void setZoneShared(boolean shared) {
2865        sharedZone = shared;
2866    }
2867
2868    /**
2869     * Specifies whether or not date/time interpretation is to be lenient.  With
2870     * lenient interpretation, a date such as "February 942, 1996" will be
2871     * treated as being equivalent to the 941st day after February 1, 1996.
2872     * With strict (non-lenient) interpretation, such dates will cause an exception to be
2873     * thrown. The default is lenient.
2874     *
2875     * @param lenient <code>true</code> if the lenient mode is to be turned
2876     * on; <code>false</code> if it is to be turned off.
2877     * @see #isLenient()
2878     * @see java.text.DateFormat#setLenient
2879     */
2880    public void setLenient(boolean lenient)
2881    {
2882        this.lenient = lenient;
2883    }
2884
2885    /**
2886     * Tells whether date/time interpretation is to be lenient.
2887     *
2888     * @return <code>true</code> if the interpretation mode of this calendar is lenient;
2889     * <code>false</code> otherwise.
2890     * @see #setLenient(boolean)
2891     */
2892    public boolean isLenient()
2893    {
2894        return lenient;
2895    }
2896
2897    /**
2898     * Sets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
2899     * <code>MONDAY</code> in France.
2900     *
2901     * @param value the given first day of the week.
2902     * @see #getFirstDayOfWeek()
2903     * @see #getMinimalDaysInFirstWeek()
2904     */
2905    public void setFirstDayOfWeek(int value)
2906    {
2907        if (firstDayOfWeek == value) {
2908            return;
2909        }
2910        firstDayOfWeek = value;
2911        invalidateWeekFields();
2912    }
2913
2914    /**
2915     * Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
2916     * <code>MONDAY</code> in France.
2917     *
2918     * @return the first day of the week.
2919     * @see #setFirstDayOfWeek(int)
2920     * @see #getMinimalDaysInFirstWeek()
2921     */
2922    public int getFirstDayOfWeek()
2923    {
2924        return firstDayOfWeek;
2925    }
2926
2927    /**
2928     * Sets what the minimal days required in the first week of the year are;
2929     * For example, if the first week is defined as one that contains the first
2930     * day of the first month of a year, call this method with value 1. If it
2931     * must be a full week, use value 7.
2932     *
2933     * @param value the given minimal days required in the first week
2934     * of the year.
2935     * @see #getMinimalDaysInFirstWeek()
2936     */
2937    public void setMinimalDaysInFirstWeek(int value)
2938    {
2939        if (minimalDaysInFirstWeek == value) {
2940            return;
2941        }
2942        minimalDaysInFirstWeek = value;
2943        invalidateWeekFields();
2944    }
2945
2946    /**
2947     * Gets what the minimal days required in the first week of the year are;
2948     * e.g., if the first week is defined as one that contains the first day
2949     * of the first month of a year, this method returns 1. If
2950     * the minimal days required must be a full week, this method
2951     * returns 7.
2952     *
2953     * @return the minimal days required in the first week of the year.
2954     * @see #setMinimalDaysInFirstWeek(int)
2955     */
2956    public int getMinimalDaysInFirstWeek()
2957    {
2958        return minimalDaysInFirstWeek;
2959    }
2960
2961    /**
2962     * Returns whether this {@code Calendar} supports week dates.
2963     *
2964     * <p>The default implementation of this method returns {@code false}.
2965     *
2966     * @return {@code true} if this {@code Calendar} supports week dates;
2967     *         {@code false} otherwise.
2968     * @see #getWeekYear()
2969     * @see #setWeekDate(int,int,int)
2970     * @see #getWeeksInWeekYear()
2971     * @since 1.7
2972     */
2973    public boolean isWeekDateSupported() {
2974        return false;
2975    }
2976
2977    /**
2978     * Returns the week year represented by this {@code Calendar}. The
2979     * week year is in sync with the week cycle. The {@linkplain
2980     * #getFirstDayOfWeek() first day of the first week} is the first
2981     * day of the week year.
2982     *
2983     * <p>The default implementation of this method throws an
2984     * {@link UnsupportedOperationException}.
2985     *
2986     * @return the week year of this {@code Calendar}
2987     * @exception UnsupportedOperationException
2988     *            if any week year numbering isn't supported
2989     *            in this {@code Calendar}.
2990     * @see #isWeekDateSupported()
2991     * @see #getFirstDayOfWeek()
2992     * @see #getMinimalDaysInFirstWeek()
2993     * @since 1.7
2994     */
2995    public int getWeekYear() {
2996        throw new UnsupportedOperationException();
2997    }
2998
2999    /**
3000     * Sets the date of this {@code Calendar} with the the given date
3001     * specifiers - week year, week of year, and day of week.
3002     *
3003     * <p>Unlike the {@code set} method, all of the calendar fields
3004     * and {@code time} values are calculated upon return.
3005     *
3006     * <p>If {@code weekOfYear} is out of the valid week-of-year range
3007     * in {@code weekYear}, the {@code weekYear} and {@code
3008     * weekOfYear} values are adjusted in lenient mode, or an {@code
3009     * IllegalArgumentException} is thrown in non-lenient mode.
3010     *
3011     * <p>The default implementation of this method throws an
3012     * {@code UnsupportedOperationException}.
3013     *
3014     * @param weekYear   the week year
3015     * @param weekOfYear the week number based on {@code weekYear}
3016     * @param dayOfWeek  the day of week value: one of the constants
3017     *                   for the {@link #DAY_OF_WEEK} field: {@link
3018     *                   #SUNDAY}, ..., {@link #SATURDAY}.
3019     * @exception IllegalArgumentException
3020     *            if any of the given date specifiers is invalid
3021     *            or any of the calendar fields are inconsistent
3022     *            with the given date specifiers in non-lenient mode
3023     * @exception UnsupportedOperationException
3024     *            if any week year numbering isn't supported in this
3025     *            {@code Calendar}.
3026     * @see #isWeekDateSupported()
3027     * @see #getFirstDayOfWeek()
3028     * @see #getMinimalDaysInFirstWeek()
3029     * @since 1.7
3030     */
3031    public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
3032        throw new UnsupportedOperationException();
3033    }
3034
3035    /**
3036     * Returns the number of weeks in the week year represented by this
3037     * {@code Calendar}.
3038     *
3039     * <p>The default implementation of this method throws an
3040     * {@code UnsupportedOperationException}.
3041     *
3042     * @return the number of weeks in the week year.
3043     * @exception UnsupportedOperationException
3044     *            if any week year numbering isn't supported in this
3045     *            {@code Calendar}.
3046     * @see #WEEK_OF_YEAR
3047     * @see #isWeekDateSupported()
3048     * @see #getWeekYear()
3049     * @see #getActualMaximum(int)
3050     * @since 1.7
3051     */
3052    public int getWeeksInWeekYear() {
3053        throw new UnsupportedOperationException();
3054    }
3055
3056    /**
3057     * Returns the minimum value for the given calendar field of this
3058     * <code>Calendar</code> instance. The minimum value is defined as
3059     * the smallest value returned by the {@link #get(int) get} method
3060     * for any possible time value.  The minimum value depends on
3061     * calendar system specific parameters of the instance.
3062     *
3063     * @param field the calendar field.
3064     * @return the minimum value for the given calendar field.
3065     * @see #getMaximum(int)
3066     * @see #getGreatestMinimum(int)
3067     * @see #getLeastMaximum(int)
3068     * @see #getActualMinimum(int)
3069     * @see #getActualMaximum(int)
3070     */
3071    abstract public int getMinimum(int field);
3072
3073    /**
3074     * Returns the maximum value for the given calendar field of this
3075     * <code>Calendar</code> instance. The maximum value is defined as
3076     * the largest value returned by the {@link #get(int) get} method
3077     * for any possible time value. The maximum value depends on
3078     * calendar system specific parameters of the instance.
3079     *
3080     * @param field the calendar field.
3081     * @return the maximum value for the given calendar field.
3082     * @see #getMinimum(int)
3083     * @see #getGreatestMinimum(int)
3084     * @see #getLeastMaximum(int)
3085     * @see #getActualMinimum(int)
3086     * @see #getActualMaximum(int)
3087     */
3088    abstract public int getMaximum(int field);
3089
3090    /**
3091     * Returns the highest minimum value for the given calendar field
3092     * of this <code>Calendar</code> instance. The highest minimum
3093     * value is defined as the largest value returned by {@link
3094     * #getActualMinimum(int)} for any possible time value. The
3095     * greatest minimum value depends on calendar system specific
3096     * parameters of the instance.
3097     *
3098     * @param field the calendar field.
3099     * @return the highest minimum value for the given calendar field.
3100     * @see #getMinimum(int)
3101     * @see #getMaximum(int)
3102     * @see #getLeastMaximum(int)
3103     * @see #getActualMinimum(int)
3104     * @see #getActualMaximum(int)
3105     */
3106    abstract public int getGreatestMinimum(int field);
3107
3108    /**
3109     * Returns the lowest maximum value for the given calendar field
3110     * of this <code>Calendar</code> instance. The lowest maximum
3111     * value is defined as the smallest value returned by {@link
3112     * #getActualMaximum(int)} for any possible time value. The least
3113     * maximum value depends on calendar system specific parameters of
3114     * the instance. For example, a <code>Calendar</code> for the
3115     * Gregorian calendar system returns 28 for the
3116     * <code>DAY_OF_MONTH</code> field, because the 28th is the last
3117     * day of the shortest month of this calendar, February in a
3118     * common year.
3119     *
3120     * @param field the calendar field.
3121     * @return the lowest maximum value for the given calendar field.
3122     * @see #getMinimum(int)
3123     * @see #getMaximum(int)
3124     * @see #getGreatestMinimum(int)
3125     * @see #getActualMinimum(int)
3126     * @see #getActualMaximum(int)
3127     */
3128    abstract public int getLeastMaximum(int field);
3129
3130    /**
3131     * Returns the minimum value that the specified calendar field
3132     * could have, given the time value of this <code>Calendar</code>.
3133     *
3134     * <p>The default implementation of this method uses an iterative
3135     * algorithm to determine the actual minimum value for the
3136     * calendar field. Subclasses should, if possible, override this
3137     * with a more efficient implementation - in many cases, they can
3138     * simply return <code>getMinimum()</code>.
3139     *
3140     * @param field the calendar field
3141     * @return the minimum of the given calendar field for the time
3142     * value of this <code>Calendar</code>
3143     * @see #getMinimum(int)
3144     * @see #getMaximum(int)
3145     * @see #getGreatestMinimum(int)
3146     * @see #getLeastMaximum(int)
3147     * @see #getActualMaximum(int)
3148     * @since 1.2
3149     */
3150    public int getActualMinimum(int field) {
3151        int fieldValue = getGreatestMinimum(field);
3152        int endValue = getMinimum(field);
3153
3154        // if we know that the minimum value is always the same, just return it
3155        if (fieldValue == endValue) {
3156            return fieldValue;
3157        }
3158
3159        // clone the calendar so we don't mess with the real one, and set it to
3160        // accept anything for the field values
3161        Calendar work = (Calendar)this.clone();
3162        work.setLenient(true);
3163
3164        // now try each value from getLeastMaximum() to getMaximum() one by one until
3165        // we get a value that normalizes to another value.  The last value that
3166        // normalizes to itself is the actual minimum for the current date
3167        int result = fieldValue;
3168
3169        do {
3170            work.set(field, fieldValue);
3171            if (work.get(field) != fieldValue) {
3172                break;
3173            } else {
3174                result = fieldValue;
3175                fieldValue--;
3176            }
3177        } while (fieldValue >= endValue);
3178
3179        return result;
3180    }
3181
3182    /**
3183     * Returns the maximum value that the specified calendar field
3184     * could have, given the time value of this
3185     * <code>Calendar</code>. For example, the actual maximum value of
3186     * the <code>MONTH</code> field is 12 in some years, and 13 in
3187     * other years in the Hebrew calendar system.
3188     *
3189     * <p>The default implementation of this method uses an iterative
3190     * algorithm to determine the actual maximum value for the
3191     * calendar field. Subclasses should, if possible, override this
3192     * with a more efficient implementation.
3193     *
3194     * @param field the calendar field
3195     * @return the maximum of the given calendar field for the time
3196     * value of this <code>Calendar</code>
3197     * @see #getMinimum(int)
3198     * @see #getMaximum(int)
3199     * @see #getGreatestMinimum(int)
3200     * @see #getLeastMaximum(int)
3201     * @see #getActualMinimum(int)
3202     * @since 1.2
3203     */
3204    public int getActualMaximum(int field) {
3205        int fieldValue = getLeastMaximum(field);
3206        int endValue = getMaximum(field);
3207
3208        // if we know that the maximum value is always the same, just return it.
3209        if (fieldValue == endValue) {
3210            return fieldValue;
3211        }
3212
3213        // clone the calendar so we don't mess with the real one, and set it to
3214        // accept anything for the field values.
3215        Calendar work = (Calendar)this.clone();
3216        work.setLenient(true);
3217
3218        // if we're counting weeks, set the day of the week to Sunday.  We know the
3219        // last week of a month or year will contain the first day of the week.
3220        if (field == WEEK_OF_YEAR || field == WEEK_OF_MONTH) {
3221            work.set(DAY_OF_WEEK, firstDayOfWeek);
3222        }
3223
3224        // now try each value from getLeastMaximum() to getMaximum() one by one until
3225        // we get a value that normalizes to another value.  The last value that
3226        // normalizes to itself is the actual maximum for the current date
3227        int result = fieldValue;
3228
3229        do {
3230            work.set(field, fieldValue);
3231            if (work.get(field) != fieldValue) {
3232                break;
3233            } else {
3234                result = fieldValue;
3235                fieldValue++;
3236            }
3237        } while (fieldValue <= endValue);
3238
3239        return result;
3240    }
3241
3242    /**
3243     * Creates and returns a copy of this object.
3244     *
3245     * @return a copy of this object.
3246     */
3247    @Override
3248    public Object clone()
3249    {
3250        try {
3251            Calendar other = (Calendar) super.clone();
3252
3253            other.fields = new int[FIELD_COUNT];
3254            other.isSet = new boolean[FIELD_COUNT];
3255            other.stamp = new int[FIELD_COUNT];
3256            for (int i = 0; i < FIELD_COUNT; i++) {
3257                other.fields[i] = fields[i];
3258                other.stamp[i] = stamp[i];
3259                other.isSet[i] = isSet[i];
3260            }
3261            other.zone = (TimeZone) zone.clone();
3262            return other;
3263        }
3264        catch (CloneNotSupportedException e) {
3265            // this shouldn't happen, since we are Cloneable
3266            throw new InternalError(e);
3267        }
3268    }
3269
3270    private static final String[] FIELD_NAME = {
3271        "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH",
3272        "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR",
3273        "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET",
3274        "DST_OFFSET"
3275    };
3276
3277    /**
3278     * Returns the name of the specified calendar field.
3279     *
3280     * @param field the calendar field
3281     * @return the calendar field name
3282     * @exception IndexOutOfBoundsException if <code>field</code> is negative,
3283     * equal to or greater then <code>FIELD_COUNT</code>.
3284     */
3285    static String getFieldName(int field) {
3286        return FIELD_NAME[field];
3287    }
3288
3289    /**
3290     * Return a string representation of this calendar. This method
3291     * is intended to be used only for debugging purposes, and the
3292     * format of the returned string may vary between implementations.
3293     * The returned string may be empty but may not be <code>null</code>.
3294     *
3295     * @return  a string representation of this calendar.
3296     */
3297    @Override
3298    public String toString() {
3299        // NOTE: BuddhistCalendar.toString() interprets the string
3300        // produced by this method so that the Gregorian year number
3301        // is substituted by its B.E. year value. It relies on
3302        // "...,YEAR=<year>,..." or "...,YEAR=?,...".
3303        StringBuilder buffer = new StringBuilder(800);
3304        buffer.append(getClass().getName()).append('[');
3305        appendValue(buffer, "time", isTimeSet, time);
3306        buffer.append(",areFieldsSet=").append(areFieldsSet);
3307        buffer.append(",areAllFieldsSet=").append(areAllFieldsSet);
3308        buffer.append(",lenient=").append(lenient);
3309        buffer.append(",zone=").append(zone);
3310        appendValue(buffer, ",firstDayOfWeek", true, (long) firstDayOfWeek);
3311        appendValue(buffer, ",minimalDaysInFirstWeek", true, (long) minimalDaysInFirstWeek);
3312        for (int i = 0; i < FIELD_COUNT; ++i) {
3313            buffer.append(',');
3314            appendValue(buffer, FIELD_NAME[i], isSet(i), (long) fields[i]);
3315        }
3316        buffer.append(']');
3317        return buffer.toString();
3318    }
3319
3320    // =======================privates===============================
3321
3322    private static void appendValue(StringBuilder sb, String item, boolean valid, long value) {
3323        sb.append(item).append('=');
3324        if (valid) {
3325            sb.append(value);
3326        } else {
3327            sb.append('?');
3328        }
3329    }
3330
3331    /**
3332     * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.
3333     * They are used to figure out the week count for a specific date for
3334     * a given locale. These must be set when a Calendar is constructed.
3335     * @param desiredLocale the given locale.
3336     */
3337    private void setWeekCountData(Locale desiredLocale)
3338    {
3339        /* try to get the Locale data from the cache */
3340        int[] data = cachedLocaleData.get(desiredLocale);
3341        if (data == null) {  /* cache miss */
3342            // Android changed: Use ICU4C to get week data.
3343            LocaleData localeData = LocaleData.get(desiredLocale);
3344            data = new int[2];
3345            data[0] = localeData.firstDayOfWeek.intValue();
3346            data[1] = localeData.minimalDaysInFirstWeek.intValue();
3347            cachedLocaleData.putIfAbsent(desiredLocale, data);
3348        }
3349        firstDayOfWeek = data[0];
3350        minimalDaysInFirstWeek = data[1];
3351    }
3352
3353    /**
3354     * Recomputes the time and updates the status fields isTimeSet
3355     * and areFieldsSet.  Callers should check isTimeSet and only
3356     * call this method if isTimeSet is false.
3357     */
3358    private void updateTime() {
3359        computeTime();
3360        // The areFieldsSet and areAllFieldsSet values are no longer
3361        // controlled here (as of 1.5).
3362        isTimeSet = true;
3363    }
3364
3365    private int compareTo(long t) {
3366        long thisTime = getMillisOf(this);
3367        return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
3368    }
3369
3370    private static long getMillisOf(Calendar calendar) {
3371        if (calendar.isTimeSet) {
3372            return calendar.time;
3373        }
3374        Calendar cal = (Calendar) calendar.clone();
3375        cal.setLenient(true);
3376        return cal.getTimeInMillis();
3377    }
3378
3379    /**
3380     * Adjusts the stamp[] values before nextStamp overflow. nextStamp
3381     * is set to the next stamp value upon the return.
3382     */
3383    private void adjustStamp() {
3384        int max = MINIMUM_USER_STAMP;
3385        int newStamp = MINIMUM_USER_STAMP;
3386
3387        for (;;) {
3388            int min = Integer.MAX_VALUE;
3389            for (int i = 0; i < stamp.length; i++) {
3390                int v = stamp[i];
3391                if (v >= newStamp && min > v) {
3392                    min = v;
3393                }
3394                if (max < v) {
3395                    max = v;
3396                }
3397            }
3398            if (max != min && min == Integer.MAX_VALUE) {
3399                break;
3400            }
3401            for (int i = 0; i < stamp.length; i++) {
3402                if (stamp[i] == min) {
3403                    stamp[i] = newStamp;
3404                }
3405            }
3406            newStamp++;
3407            if (min == max) {
3408                break;
3409            }
3410        }
3411        nextStamp = newStamp;
3412    }
3413
3414    /**
3415     * Sets the WEEK_OF_MONTH and WEEK_OF_YEAR fields to new values with the
3416     * new parameter value if they have been calculated internally.
3417     */
3418    private void invalidateWeekFields()
3419    {
3420        if (stamp[WEEK_OF_MONTH] != COMPUTED &&
3421            stamp[WEEK_OF_YEAR] != COMPUTED) {
3422            return;
3423        }
3424
3425        // We have to check the new values of these fields after changing
3426        // firstDayOfWeek and/or minimalDaysInFirstWeek. If the field values
3427        // have been changed, then set the new values. (4822110)
3428        Calendar cal = (Calendar) clone();
3429        cal.setLenient(true);
3430        cal.clear(WEEK_OF_MONTH);
3431        cal.clear(WEEK_OF_YEAR);
3432
3433        if (stamp[WEEK_OF_MONTH] == COMPUTED) {
3434            int weekOfMonth = cal.get(WEEK_OF_MONTH);
3435            if (fields[WEEK_OF_MONTH] != weekOfMonth) {
3436                fields[WEEK_OF_MONTH] = weekOfMonth;
3437            }
3438        }
3439
3440        if (stamp[WEEK_OF_YEAR] == COMPUTED) {
3441            int weekOfYear = cal.get(WEEK_OF_YEAR);
3442            if (fields[WEEK_OF_YEAR] != weekOfYear) {
3443                fields[WEEK_OF_YEAR] = weekOfYear;
3444            }
3445        }
3446    }
3447
3448    /**
3449     * Save the state of this object to a stream (i.e., serialize it).
3450     *
3451     * Ideally, <code>Calendar</code> would only write out its state data and
3452     * the current time, and not write any field data out, such as
3453     * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>,
3454     * and <code>isSet[]</code>.  <code>nextStamp</code> also should not be part
3455     * of the persistent state. Unfortunately, this didn't happen before JDK 1.1
3456     * shipped. To be compatible with JDK 1.1, we will always have to write out
3457     * the field values and state flags.  However, <code>nextStamp</code> can be
3458     * removed from the serialization stream; this will probably happen in the
3459     * near future.
3460     */
3461    private synchronized void writeObject(ObjectOutputStream stream)
3462         throws IOException
3463    {
3464        // Try to compute the time correctly, for the future (stream
3465        // version 2) in which we don't write out fields[] or isSet[].
3466        if (!isTimeSet) {
3467            try {
3468                updateTime();
3469            }
3470            catch (IllegalArgumentException e) {}
3471        }
3472
3473        // Android changed: Removed ZoneInfo support/workaround.
3474        // Write out the 1.1 FCS object.
3475        stream.defaultWriteObject();
3476    }
3477
3478    private static class CalendarAccessControlContext {
3479        private static final AccessControlContext INSTANCE;
3480        static {
3481            RuntimePermission perm = new RuntimePermission("accessClassInPackage.sun.util.calendar");
3482            PermissionCollection perms = perm.newPermissionCollection();
3483            perms.add(perm);
3484            INSTANCE = new AccessControlContext(new ProtectionDomain[] {
3485                                                    new ProtectionDomain(null, perms)
3486                                                });
3487        }
3488        private CalendarAccessControlContext() {
3489        }
3490    }
3491
3492    /**
3493     * Reconstitutes this object from a stream (i.e., deserialize it).
3494     */
3495    private void readObject(ObjectInputStream stream)
3496         throws IOException, ClassNotFoundException
3497    {
3498        final ObjectInputStream input = stream;
3499        input.defaultReadObject();
3500
3501        stamp = new int[FIELD_COUNT];
3502
3503        // Starting with version 2 (not implemented yet), we expect that
3504        // fields[], isSet[], isTimeSet, and areFieldsSet may not be
3505        // streamed out anymore.  We expect 'time' to be correct.
3506        if (serialVersionOnStream >= 2)
3507        {
3508            isTimeSet = true;
3509            if (fields == null) {
3510                fields = new int[FIELD_COUNT];
3511            }
3512            if (isSet == null) {
3513                isSet = new boolean[FIELD_COUNT];
3514            }
3515        }
3516        else if (serialVersionOnStream >= 0)
3517        {
3518            for (int i=0; i<FIELD_COUNT; ++i) {
3519                stamp[i] = isSet[i] ? COMPUTED : UNSET;
3520            }
3521        }
3522
3523        serialVersionOnStream = currentSerialVersion;
3524
3525        // Android changed: removed ZoneInfo support.
3526
3527        // If the deserialized object has a SimpleTimeZone, try to
3528        // replace it with a ZoneInfo equivalent (as of 1.4) in order
3529        // to be compatible with the SimpleTimeZone-based
3530        // implementation as much as possible.
3531        if (zone instanceof SimpleTimeZone) {
3532            String id = zone.getID();
3533            TimeZone tz = TimeZone.getTimeZone(id);
3534            if (tz != null && tz.hasSameRules(zone) && tz.getID().equals(id)) {
3535                zone = tz;
3536            }
3537        }
3538    }
3539
3540    /**
3541     * Converts this object to an {@link Instant}.
3542     * <p>
3543     * The conversion creates an {@code Instant} that represents the
3544     * same point on the time-line as this {@code Calendar}.
3545     *
3546     * @return the instant representing the same point on the time-line
3547     * @since 1.8
3548     */
3549    public final Instant toInstant() {
3550        return Instant.ofEpochMilli(getTimeInMillis());
3551    }
3552}
3553