Calendar.java revision 6975f84c2ed72e1e26d20190b6f318718c849008
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 1996, 2013, 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        // Android-changed: fix typo in example code.
1165        /**
1166         * Sets field parameters to their values given by
1167         * {@code fieldValuePairs} that are pairs of a field and its value.
1168         * For example,
1169         * <pre>
1170         *   setFields(Calendar.YEAR, 2013,
1171         *             Calendar.MONTH, Calendar.DECEMBER,
1172         *             Calendar.DAY_OF_MONTH, 23);</pre>
1173         * is equivalent to the sequence of the following
1174         * {@link #set(int, int) set} calls:
1175         * <pre>
1176         *   set(Calendar.YEAR, 2013)
1177         *   .set(Calendar.MONTH, Calendar.DECEMBER)
1178         *   .set(Calendar.DAY_OF_MONTH, 23);</pre>
1179         *
1180         * @param fieldValuePairs field-value pairs
1181         * @return this {@code Calendar.Builder}
1182         * @throws NullPointerException if {@code fieldValuePairs} is {@code null}
1183         * @throws IllegalArgumentException if any of fields are invalid,
1184         *             or if {@code fieldValuePairs.length} is an odd number.
1185         * @throws IllegalStateException    if the instant value has been set,
1186         *             or if fields have been set too many (approximately
1187         *             {@link Integer#MAX_VALUE}) times.
1188         */
1189        public Builder setFields(int... fieldValuePairs) {
1190            int len = fieldValuePairs.length;
1191            if ((len % 2) != 0) {
1192                throw new IllegalArgumentException();
1193            }
1194            if (isInstantSet()) {
1195                throw new IllegalStateException("instant has been set");
1196            }
1197            if ((nextStamp + len / 2) < 0) {
1198                throw new IllegalStateException("stamp counter overflow");
1199            }
1200            allocateFields();
1201            for (int i = 0; i < len; ) {
1202                int field = fieldValuePairs[i++];
1203                // Note: WEEK_YEAR can't be set with this method.
1204                if (field < 0 || field >= FIELD_COUNT) {
1205                    throw new IllegalArgumentException("field is invalid");
1206                }
1207                internalSet(field, fieldValuePairs[i++]);
1208            }
1209            return this;
1210        }
1211
1212        /**
1213         * Sets the date field parameters to the values given by {@code year},
1214         * {@code month}, and {@code dayOfMonth}. This method is equivalent to
1215         * a call to:
1216         * <pre>
1217         *   setFields(Calendar.YEAR, year,
1218         *             Calendar.MONTH, month,
1219         *             Calendar.DAY_OF_MONTH, dayOfMonth);</pre>
1220         *
1221         * @param year       the {@link Calendar#YEAR YEAR} value
1222         * @param month      the {@link Calendar#MONTH MONTH} value
1223         *                   (the month numbering is <em>0-based</em>).
1224         * @param dayOfMonth the {@link Calendar#DAY_OF_MONTH DAY_OF_MONTH} value
1225         * @return this {@code Calendar.Builder}
1226         */
1227        public Builder setDate(int year, int month, int dayOfMonth) {
1228            return setFields(YEAR, year, MONTH, month, DAY_OF_MONTH, dayOfMonth);
1229        }
1230
1231        /**
1232         * Sets the time of day field parameters to the values given by
1233         * {@code hourOfDay}, {@code minute}, and {@code second}. This method is
1234         * equivalent to a call to:
1235         * <pre>
1236         *   setTimeOfDay(hourOfDay, minute, second, 0);</pre>
1237         *
1238         * @param hourOfDay the {@link Calendar#HOUR_OF_DAY HOUR_OF_DAY} value
1239         *                  (24-hour clock)
1240         * @param minute    the {@link Calendar#MINUTE MINUTE} value
1241         * @param second    the {@link Calendar#SECOND SECOND} value
1242         * @return this {@code Calendar.Builder}
1243         */
1244        public Builder setTimeOfDay(int hourOfDay, int minute, int second) {
1245            return setTimeOfDay(hourOfDay, minute, second, 0);
1246        }
1247
1248        /**
1249         * Sets the time of day field parameters to the values given by
1250         * {@code hourOfDay}, {@code minute}, {@code second}, and
1251         * {@code millis}. This method is equivalent to a call to:
1252         * <pre>
1253         *   setFields(Calendar.HOUR_OF_DAY, hourOfDay,
1254         *             Calendar.MINUTE, minute,
1255         *             Calendar.SECOND, second,
1256         *             Calendar.MILLISECOND, millis);</pre>
1257         *
1258         * @param hourOfDay the {@link Calendar#HOUR_OF_DAY HOUR_OF_DAY} value
1259         *                  (24-hour clock)
1260         * @param minute    the {@link Calendar#MINUTE MINUTE} value
1261         * @param second    the {@link Calendar#SECOND SECOND} value
1262         * @param millis    the {@link Calendar#MILLISECOND MILLISECOND} value
1263         * @return this {@code Calendar.Builder}
1264         */
1265        public Builder setTimeOfDay(int hourOfDay, int minute, int second, int millis) {
1266            return setFields(HOUR_OF_DAY, hourOfDay, MINUTE, minute,
1267                             SECOND, second, MILLISECOND, millis);
1268        }
1269
1270        /**
1271         * Sets the week-based date parameters to the values with the given
1272         * date specifiers - week year, week of year, and day of week.
1273         *
1274         * <p>If the specified calendar doesn't support week dates, the
1275         * {@link #build() build} method will throw an {@link IllegalArgumentException}.
1276         *
1277         * @param weekYear   the week year
1278         * @param weekOfYear the week number based on {@code weekYear}
1279         * @param dayOfWeek  the day of week value: one of the constants
1280         *     for the {@link Calendar#DAY_OF_WEEK DAY_OF_WEEK} field:
1281         *     {@link Calendar#SUNDAY SUNDAY}, ..., {@link Calendar#SATURDAY SATURDAY}.
1282         * @return this {@code Calendar.Builder}
1283         * @see Calendar#setWeekDate(int, int, int)
1284         * @see Calendar#isWeekDateSupported()
1285         */
1286        public Builder setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
1287            allocateFields();
1288            internalSet(WEEK_YEAR, weekYear);
1289            internalSet(WEEK_OF_YEAR, weekOfYear);
1290            internalSet(DAY_OF_WEEK, dayOfWeek);
1291            return this;
1292        }
1293
1294        /**
1295         * Sets the time zone parameter to the given {@code zone}. If no time
1296         * zone parameter is given to this {@code Caledar.Builder}, the
1297         * {@linkplain TimeZone#getDefault() default
1298         * <code>TimeZone</code>} will be used in the {@link #build() build}
1299         * method.
1300         *
1301         * @param zone the {@link TimeZone}
1302         * @return this {@code Calendar.Builder}
1303         * @throws NullPointerException if {@code zone} is {@code null}
1304         * @see Calendar#setTimeZone(TimeZone)
1305         */
1306        public Builder setTimeZone(TimeZone zone) {
1307            if (zone == null) {
1308                throw new NullPointerException();
1309            }
1310            this.zone = zone;
1311            return this;
1312        }
1313
1314        /**
1315         * Sets the lenient mode parameter to the value given by {@code lenient}.
1316         * If no lenient parameter is given to this {@code Calendar.Builder},
1317         * lenient mode will be used in the {@link #build() build} method.
1318         *
1319         * @param lenient {@code true} for lenient mode;
1320         *                {@code false} for non-lenient mode
1321         * @return this {@code Calendar.Builder}
1322         * @see Calendar#setLenient(boolean)
1323         */
1324        public Builder setLenient(boolean lenient) {
1325            this.lenient = lenient;
1326            return this;
1327        }
1328
1329        /**
1330         * Sets the calendar type parameter to the given {@code type}. The
1331         * calendar type given by this method has precedence over any explicit
1332         * or implicit calendar type given by the
1333         * {@linkplain #setLocale(Locale) locale}.
1334         *
1335         * <p>In addition to the available calendar types returned by the
1336         * {@link Calendar#getAvailableCalendarTypes() Calendar.getAvailableCalendarTypes}
1337         * method, {@code "gregorian"} and {@code "iso8601"} as aliases of
1338         * {@code "gregory"} can be used with this method.
1339         *
1340         * @param type the calendar type
1341         * @return this {@code Calendar.Builder}
1342         * @throws NullPointerException if {@code type} is {@code null}
1343         * @throws IllegalArgumentException if {@code type} is unknown
1344         * @throws IllegalStateException if another calendar type has already been set
1345         * @see Calendar#getCalendarType()
1346         * @see Calendar#getAvailableCalendarTypes()
1347         */
1348        public Builder setCalendarType(String type) {
1349            if (type.equals("gregorian")) { // NPE if type == null
1350                type = "gregory";
1351            }
1352            if (!Calendar.getAvailableCalendarTypes().contains(type)
1353                    && !type.equals("iso8601")) {
1354                throw new IllegalArgumentException("unknown calendar type: " + type);
1355            }
1356            if (this.type == null) {
1357                this.type = type;
1358            } else {
1359                if (!this.type.equals(type)) {
1360                    throw new IllegalStateException("calendar type override");
1361                }
1362            }
1363            return this;
1364        }
1365
1366        /**
1367         * Sets the locale parameter to the given {@code locale}. If no locale
1368         * is given to this {@code Calendar.Builder}, the {@linkplain
1369         * Locale#getDefault(Locale.Category) default <code>Locale</code>}
1370         * for {@link Locale.Category#FORMAT} will be used.
1371         *
1372         * <p>If no calendar type is explicitly given by a call to the
1373         * {@link #setCalendarType(String) setCalendarType} method,
1374         * the {@code Locale} value is used to determine what type of
1375         * {@code Calendar} to be built.
1376         *
1377         * <p>If no week definition parameters are explicitly given by a call to
1378         * the {@link #setWeekDefinition(int,int) setWeekDefinition} method, the
1379         * {@code Locale}'s default values are used.
1380         *
1381         * @param locale the {@link Locale}
1382         * @throws NullPointerException if {@code locale} is {@code null}
1383         * @return this {@code Calendar.Builder}
1384         * @see Calendar#getInstance(Locale)
1385         */
1386        public Builder setLocale(Locale locale) {
1387            if (locale == null) {
1388                throw new NullPointerException();
1389            }
1390            this.locale = locale;
1391            return this;
1392        }
1393
1394        /**
1395         * Sets the week definition parameters to the values given by
1396         * {@code firstDayOfWeek} and {@code minimalDaysInFirstWeek} that are
1397         * used to determine the <a href="Calendar.html#First_Week">first
1398         * week</a> of a year. The parameters given by this method have
1399         * precedence over the default values given by the
1400         * {@linkplain #setLocale(Locale) locale}.
1401         *
1402         * @param firstDayOfWeek the first day of a week; one of
1403         *                       {@link Calendar#SUNDAY} to {@link Calendar#SATURDAY}
1404         * @param minimalDaysInFirstWeek the minimal number of days in the first
1405         *                               week (1..7)
1406         * @return this {@code Calendar.Builder}
1407         * @throws IllegalArgumentException if {@code firstDayOfWeek} or
1408         *                                  {@code minimalDaysInFirstWeek} is invalid
1409         * @see Calendar#getFirstDayOfWeek()
1410         * @see Calendar#getMinimalDaysInFirstWeek()
1411         */
1412        public Builder setWeekDefinition(int firstDayOfWeek, int minimalDaysInFirstWeek) {
1413            if (!isValidWeekParameter(firstDayOfWeek)
1414                    || !isValidWeekParameter(minimalDaysInFirstWeek)) {
1415                throw new IllegalArgumentException();
1416            }
1417            this.firstDayOfWeek = firstDayOfWeek;
1418            this.minimalDaysInFirstWeek = minimalDaysInFirstWeek;
1419            return this;
1420        }
1421
1422        /**
1423         * Returns a {@code Calendar} built from the parameters set by the
1424         * setter methods. The calendar type given by the {@link #setCalendarType(String)
1425         * setCalendarType} method or the {@linkplain #setLocale(Locale) locale} is
1426         * used to determine what {@code Calendar} to be created. If no explicit
1427         * calendar type is given, the locale's default calendar is created.
1428         *
1429         * <p>If the calendar type is {@code "iso8601"}, the
1430         * {@linkplain GregorianCalendar#setGregorianChange(Date) Gregorian change date}
1431         * of a {@link GregorianCalendar} is set to {@code Date(Long.MIN_VALUE)}
1432         * to be the <em>proleptic</em> Gregorian calendar. Its week definition
1433         * parameters are also set to be <a
1434         * href="GregorianCalendar.html#iso8601_compatible_setting">compatible
1435         * with the ISO 8601 standard</a>. Note that the
1436         * {@link GregorianCalendar#getCalendarType() getCalendarType} method of
1437         * a {@code GregorianCalendar} created with {@code "iso8601"} returns
1438         * {@code "gregory"}.
1439         *
1440         * <p>The default values are used for locale and time zone if these
1441         * parameters haven't been given explicitly.
1442         *
1443         * <p>Any out of range field values are either normalized in lenient
1444         * mode or detected as an invalid value in non-lenient mode.
1445         *
1446         * @return a {@code Calendar} built with parameters of this {@code
1447         *         Calendar.Builder}
1448         * @throws IllegalArgumentException if the calendar type is unknown, or
1449         *             if any invalid field values are given in non-lenient mode, or
1450         *             if a week date is given for the calendar type that doesn't
1451         *             support week dates.
1452         * @see Calendar#getInstance(TimeZone, Locale)
1453         * @see Locale#getDefault(Locale.Category)
1454         * @see TimeZone#getDefault()
1455         */
1456        public Calendar build() {
1457            if (locale == null) {
1458                locale = Locale.getDefault();
1459            }
1460            if (zone == null) {
1461                zone = TimeZone.getDefault();
1462            }
1463            Calendar cal;
1464            if (type == null) {
1465                type = locale.getUnicodeLocaleType("ca");
1466            }
1467            if (type == null) {
1468                // Android-changed: don't switch to buddhist calendar based on locale.
1469                // See http://b/35138741
1470                /*
1471                if (locale.getCountry() == "TH"
1472                        && locale.getLanguage() == "th") {
1473                    type = "buddhist";
1474                } else {
1475                    type = "gregory";
1476                }
1477                */
1478                type = "gregory";
1479            }
1480            switch (type) {
1481            case "gregory":
1482                cal = new GregorianCalendar(zone, locale, true);
1483                break;
1484            case "iso8601":
1485                GregorianCalendar gcal = new GregorianCalendar(zone, locale, true);
1486                // make gcal a proleptic Gregorian
1487                gcal.setGregorianChange(new Date(Long.MIN_VALUE));
1488                // and week definition to be compatible with ISO 8601
1489                setWeekDefinition(MONDAY, 4);
1490                cal = gcal;
1491                break;
1492// BEGIN Android-changed: removed support for "buddhist" and "japanese".
1493//            case "buddhist":
1494//                cal = new BuddhistCalendar(zone, locale);
1495//                cal.clear();
1496//                break;
1497//            case "japanese":
1498//                cal = new JapaneseImperialCalendar(zone, locale, true);
1499//                break;
1500// END Android-changed: removed support for "buddhist" and "japanese".
1501            default:
1502                throw new IllegalArgumentException("unknown calendar type: " + type);
1503            }
1504            cal.setLenient(lenient);
1505            if (firstDayOfWeek != 0) {
1506                cal.setFirstDayOfWeek(firstDayOfWeek);
1507                cal.setMinimalDaysInFirstWeek(minimalDaysInFirstWeek);
1508            }
1509            if (isInstantSet()) {
1510                cal.setTimeInMillis(instant);
1511                cal.complete();
1512                return cal;
1513            }
1514
1515            if (fields != null) {
1516                boolean weekDate = isSet(WEEK_YEAR)
1517                                       && fields[WEEK_YEAR] > fields[YEAR];
1518                if (weekDate && !cal.isWeekDateSupported()) {
1519                    throw new IllegalArgumentException("week date is unsupported by " + type);
1520                }
1521
1522                // Set the fields from the min stamp to the max stamp so that
1523                // the fields resolution works in the Calendar.
1524                for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {
1525                    for (int index = 0; index <= maxFieldIndex; index++) {
1526                        if (fields[index] == stamp) {
1527                            cal.set(index, fields[NFIELDS + index]);
1528                            break;
1529                        }
1530                    }
1531                }
1532
1533                if (weekDate) {
1534                    int weekOfYear = isSet(WEEK_OF_YEAR) ? fields[NFIELDS + WEEK_OF_YEAR] : 1;
1535                    int dayOfWeek = isSet(DAY_OF_WEEK)
1536                                    ? fields[NFIELDS + DAY_OF_WEEK] : cal.getFirstDayOfWeek();
1537                    cal.setWeekDate(fields[NFIELDS + WEEK_YEAR], weekOfYear, dayOfWeek);
1538                }
1539                cal.complete();
1540            }
1541
1542            return cal;
1543        }
1544
1545        private void allocateFields() {
1546            if (fields == null) {
1547                fields = new int[NFIELDS * 2];
1548                nextStamp = MINIMUM_USER_STAMP;
1549                maxFieldIndex = -1;
1550            }
1551        }
1552
1553        private void internalSet(int field, int value) {
1554            fields[field] = nextStamp++;
1555            if (nextStamp < 0) {
1556                throw new IllegalStateException("stamp counter overflow");
1557            }
1558            fields[NFIELDS + field] = value;
1559            if (field > maxFieldIndex && field < WEEK_YEAR) {
1560                maxFieldIndex = field;
1561            }
1562        }
1563
1564        private boolean isInstantSet() {
1565            return nextStamp == COMPUTED;
1566        }
1567
1568        private boolean isSet(int index) {
1569            return fields != null && fields[index] > UNSET;
1570        }
1571
1572        private boolean isValidWeekParameter(int value) {
1573            return value > 0 && value <= 7;
1574        }
1575    }
1576
1577    /**
1578     * Constructs a Calendar with the default time zone
1579     * and the default {@link java.util.Locale.Category#FORMAT FORMAT}
1580     * locale.
1581     * @see     TimeZone#getDefault
1582     */
1583    protected Calendar()
1584    {
1585        this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
1586        sharedZone = true;
1587    }
1588
1589    /**
1590     * Constructs a calendar with the specified time zone and locale.
1591     *
1592     * @param zone the time zone to use
1593     * @param aLocale the locale for the week data
1594     */
1595    protected Calendar(TimeZone zone, Locale aLocale)
1596    {
1597        // BEGIN Android-added: Allow aLocale == null
1598        // http://b/16938922.
1599        //
1600        // TODO: This is for backwards compatibility only. Seems like a better idea to throw
1601        // here. We should add a targetSdkVersion based check and throw for this case.
1602        if (aLocale == null) {
1603            aLocale = Locale.getDefault();
1604        }
1605        // END Android-added: Allow aLocale == null
1606        fields = new int[FIELD_COUNT];
1607        isSet = new boolean[FIELD_COUNT];
1608        stamp = new int[FIELD_COUNT];
1609
1610        this.zone = zone;
1611        setWeekCountData(aLocale);
1612    }
1613
1614    /**
1615     * Gets a calendar using the default time zone and locale. The
1616     * <code>Calendar</code> returned is based on the current time
1617     * in the default time zone with the default
1618     * {@link Locale.Category#FORMAT FORMAT} locale.
1619     *
1620     * @return a Calendar.
1621     */
1622    public static Calendar getInstance()
1623    {
1624        return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
1625    }
1626
1627    /**
1628     * Gets a calendar using the specified time zone and default locale.
1629     * The <code>Calendar</code> returned is based on the current time
1630     * in the given time zone with the default
1631     * {@link Locale.Category#FORMAT FORMAT} locale.
1632     *
1633     * @param zone the time zone to use
1634     * @return a Calendar.
1635     */
1636    public static Calendar getInstance(TimeZone zone)
1637    {
1638        return createCalendar(zone, Locale.getDefault(Locale.Category.FORMAT));
1639    }
1640
1641    /**
1642     * Gets a calendar using the default time zone and specified locale.
1643     * The <code>Calendar</code> returned is based on the current time
1644     * in the default time zone with the given locale.
1645     *
1646     * @param aLocale the locale for the week data
1647     * @return a Calendar.
1648     */
1649    public static Calendar getInstance(Locale aLocale)
1650    {
1651        return createCalendar(TimeZone.getDefault(), aLocale);
1652    }
1653
1654    /**
1655     * Gets a calendar with the specified time zone and locale.
1656     * The <code>Calendar</code> returned is based on the current time
1657     * in the given time zone with the given locale.
1658     *
1659     * @param zone the time zone to use
1660     * @param aLocale the locale for the week data
1661     * @return a Calendar.
1662     */
1663    public static Calendar getInstance(TimeZone zone,
1664                                       Locale aLocale)
1665    {
1666        return createCalendar(zone, aLocale);
1667    }
1668
1669    // BEGIN Android-added: add getJapaneseImperialInstance()
1670    /**
1671     * Create a Japanese Imperial Calendar.
1672     * @hide
1673     */
1674    public static Calendar getJapaneseImperialInstance(TimeZone zone, Locale aLocale) {
1675        return new JapaneseImperialCalendar(zone, aLocale);
1676    }
1677    // END Android-added: add getJapaneseImperialInstance()
1678
1679    private static Calendar createCalendar(TimeZone zone,
1680                                           Locale aLocale)
1681    {
1682        // BEGIN Android-changed: only support GregorianCalendar here
1683        return new GregorianCalendar(zone, aLocale);
1684        // END Android-changed: only support GregorianCalendar here
1685    }
1686
1687    /**
1688     * Returns an array of all locales for which the <code>getInstance</code>
1689     * methods of this class can return localized instances.
1690     * The array returned must contain at least a <code>Locale</code>
1691     * instance equal to {@link java.util.Locale#US Locale.US}.
1692     *
1693     * @return An array of locales for which localized
1694     *         <code>Calendar</code> instances are available.
1695     */
1696    public static synchronized Locale[] getAvailableLocales()
1697    {
1698        return DateFormat.getAvailableLocales();
1699    }
1700
1701    /**
1702     * Converts the current calendar field values in {@link #fields fields[]}
1703     * to the millisecond time value
1704     * {@link #time}.
1705     *
1706     * @see #complete()
1707     * @see #computeFields()
1708     */
1709    protected abstract void computeTime();
1710
1711    /**
1712     * Converts the current millisecond time value {@link #time}
1713     * to calendar field values in {@link #fields fields[]}.
1714     * This allows you to sync up the calendar field values with
1715     * a new time that is set for the calendar.  The time is <em>not</em>
1716     * recomputed first; to recompute the time, then the fields, call the
1717     * {@link #complete()} method.
1718     *
1719     * @see #computeTime()
1720     */
1721    protected abstract void computeFields();
1722
1723    /**
1724     * Returns a <code>Date</code> object representing this
1725     * <code>Calendar</code>'s time value (millisecond offset from the <a
1726     * href="#Epoch">Epoch</a>").
1727     *
1728     * @return a <code>Date</code> representing the time value.
1729     * @see #setTime(Date)
1730     * @see #getTimeInMillis()
1731     */
1732    public final Date getTime() {
1733        return new Date(getTimeInMillis());
1734    }
1735
1736    /**
1737     * Sets this Calendar's time with the given <code>Date</code>.
1738     * <p>
1739     * Note: Calling <code>setTime()</code> with
1740     * <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code>
1741     * may yield incorrect field values from <code>get()</code>.
1742     *
1743     * @param date the given Date.
1744     * @see #getTime()
1745     * @see #setTimeInMillis(long)
1746     */
1747    public final void setTime(Date date) {
1748        setTimeInMillis(date.getTime());
1749    }
1750
1751    /**
1752     * Returns this Calendar's time value in milliseconds.
1753     *
1754     * @return the current time as UTC milliseconds from the epoch.
1755     * @see #getTime()
1756     * @see #setTimeInMillis(long)
1757     */
1758    public long getTimeInMillis() {
1759        if (!isTimeSet) {
1760            updateTime();
1761        }
1762        return time;
1763    }
1764
1765    /**
1766     * Sets this Calendar's current time from the given long value.
1767     *
1768     * @param millis the new time in UTC milliseconds from the epoch.
1769     * @see #setTime(Date)
1770     * @see #getTimeInMillis()
1771     */
1772    public void setTimeInMillis(long millis) {
1773        // If we don't need to recalculate the calendar field values,
1774        // do nothing.
1775// BEGIN Android-changed: Removed ZoneInfo support
1776        if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet) {
1777//        if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet
1778//            && (zone instanceof ZoneInfo) && !((ZoneInfo)zone).isDirty()) {
1779// END Android-changed: Removed ZoneInfo support
1780
1781            return;
1782        }
1783        time = millis;
1784        isTimeSet = true;
1785        areFieldsSet = false;
1786        computeFields();
1787        areAllFieldsSet = areFieldsSet = true;
1788    }
1789
1790    /**
1791     * Returns the value of the given calendar field. In lenient mode,
1792     * all calendar fields are normalized. In non-lenient mode, all
1793     * calendar fields are validated and this method throws an
1794     * exception if any calendar fields have out-of-range values. The
1795     * normalization and validation are handled by the
1796     * {@link #complete()} method, which process is calendar
1797     * system dependent.
1798     *
1799     * @param field the given calendar field.
1800     * @return the value for the given calendar field.
1801     * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
1802     *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1803     * @see #set(int,int)
1804     * @see #complete()
1805     */
1806    public int get(int field)
1807    {
1808        complete();
1809        return internalGet(field);
1810    }
1811
1812    /**
1813     * Returns the value of the given calendar field. This method does
1814     * not involve normalization or validation of the field value.
1815     *
1816     * @param field the given calendar field.
1817     * @return the value for the given calendar field.
1818     * @see #get(int)
1819     */
1820    protected final int internalGet(int field)
1821    {
1822        return fields[field];
1823    }
1824
1825    /**
1826     * Sets the value of the given calendar field. This method does
1827     * not affect any setting state of the field in this
1828     * <code>Calendar</code> instance.
1829     *
1830     * @throws IndexOutOfBoundsException if the specified field is out of range
1831     *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1832     * @see #areFieldsSet
1833     * @see #isTimeSet
1834     * @see #areAllFieldsSet
1835     * @see #set(int,int)
1836     */
1837    final void internalSet(int field, int value)
1838    {
1839        fields[field] = value;
1840    }
1841
1842    /**
1843     * Sets the given calendar field to the given value. The value is not
1844     * interpreted by this method regardless of the leniency mode.
1845     *
1846     * @param field the given calendar field.
1847     * @param value the value to be set for the given calendar field.
1848     * @throws ArrayIndexOutOfBoundsException if the specified field is out of range
1849     *             (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
1850     * in non-lenient mode.
1851     * @see #set(int,int,int)
1852     * @see #set(int,int,int,int,int)
1853     * @see #set(int,int,int,int,int,int)
1854     * @see #get(int)
1855     */
1856    public void set(int field, int value)
1857    {
1858        // If the fields are partially normalized, calculate all the
1859        // fields before changing any fields.
1860        if (areFieldsSet && !areAllFieldsSet) {
1861            computeFields();
1862        }
1863        internalSet(field, value);
1864        isTimeSet = false;
1865        areFieldsSet = false;
1866        isSet[field] = true;
1867        stamp[field] = nextStamp++;
1868        if (nextStamp == Integer.MAX_VALUE) {
1869            adjustStamp();
1870        }
1871    }
1872
1873    /**
1874     * Sets the values for the calendar fields <code>YEAR</code>,
1875     * <code>MONTH</code>, and <code>DAY_OF_MONTH</code>.
1876     * Previous values of other calendar fields are retained.  If this is not desired,
1877     * call {@link #clear()} first.
1878     *
1879     * @param year the value used to set the <code>YEAR</code> calendar field.
1880     * @param month the value used to set the <code>MONTH</code> calendar field.
1881     * Month value is 0-based. e.g., 0 for January.
1882     * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1883     * @see #set(int,int)
1884     * @see #set(int,int,int,int,int)
1885     * @see #set(int,int,int,int,int,int)
1886     */
1887    public final void set(int year, int month, int date)
1888    {
1889        set(YEAR, year);
1890        set(MONTH, month);
1891        set(DATE, date);
1892    }
1893
1894    /**
1895     * Sets the values for the calendar fields <code>YEAR</code>,
1896     * <code>MONTH</code>, <code>DAY_OF_MONTH</code>,
1897     * <code>HOUR_OF_DAY</code>, and <code>MINUTE</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     * @see #set(int,int)
1908     * @see #set(int,int,int)
1909     * @see #set(int,int,int,int,int,int)
1910     */
1911    public final void set(int year, int month, int date, int hourOfDay, int minute)
1912    {
1913        set(YEAR, year);
1914        set(MONTH, month);
1915        set(DATE, date);
1916        set(HOUR_OF_DAY, hourOfDay);
1917        set(MINUTE, minute);
1918    }
1919
1920    /**
1921     * Sets the values for the fields <code>YEAR</code>, <code>MONTH</code>,
1922     * <code>DAY_OF_MONTH</code>, <code>HOUR_OF_DAY</code>, <code>MINUTE</code>, and
1923     * <code>SECOND</code>.
1924     * Previous values of other fields are retained.  If this is not desired,
1925     * call {@link #clear()} first.
1926     *
1927     * @param year the value used to set the <code>YEAR</code> calendar field.
1928     * @param month the value used to set the <code>MONTH</code> calendar field.
1929     * Month value is 0-based. e.g., 0 for January.
1930     * @param date the value used to set the <code>DAY_OF_MONTH</code> calendar field.
1931     * @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field.
1932     * @param minute the value used to set the <code>MINUTE</code> calendar field.
1933     * @param second the value used to set the <code>SECOND</code> calendar field.
1934     * @see #set(int,int)
1935     * @see #set(int,int,int)
1936     * @see #set(int,int,int,int,int)
1937     */
1938    public final void set(int year, int month, int date, int hourOfDay, int minute,
1939                          int second)
1940    {
1941        set(YEAR, year);
1942        set(MONTH, month);
1943        set(DATE, date);
1944        set(HOUR_OF_DAY, hourOfDay);
1945        set(MINUTE, minute);
1946        set(SECOND, second);
1947    }
1948
1949    /**
1950     * Sets all the calendar field values and the time value
1951     * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
1952     * this <code>Calendar</code> undefined. This means that {@link
1953     * #isSet(int) isSet()} will return <code>false</code> for all the
1954     * calendar fields, and the date and time calculations will treat
1955     * the fields as if they had never been set. A
1956     * <code>Calendar</code> implementation class may use its specific
1957     * default field values for date/time calculations. For example,
1958     * <code>GregorianCalendar</code> uses 1970 if the
1959     * <code>YEAR</code> field value is undefined.
1960     *
1961     * @see #clear(int)
1962     */
1963    public final void clear()
1964    {
1965        for (int i = 0; i < fields.length; ) {
1966            stamp[i] = fields[i] = 0; // UNSET == 0
1967            isSet[i++] = false;
1968        }
1969        areAllFieldsSet = areFieldsSet = false;
1970        isTimeSet = false;
1971    }
1972
1973    /**
1974     * Sets the given calendar field value and the time value
1975     * (millisecond offset from the <a href="#Epoch">Epoch</a>) of
1976     * this <code>Calendar</code> undefined. This means that {@link
1977     * #isSet(int) isSet(field)} will return <code>false</code>, and
1978     * the date and time calculations will treat the field as if it
1979     * had never been set. A <code>Calendar</code> implementation
1980     * class may use the field's specific default value for date and
1981     * time calculations.
1982     *
1983     * <p>The {@link #HOUR_OF_DAY}, {@link #HOUR} and {@link #AM_PM}
1984     * fields are handled independently and the <a
1985     * href="#time_resolution">the resolution rule for the time of
1986     * day</a> is applied. Clearing one of the fields doesn't reset
1987     * the hour of day value of this <code>Calendar</code>. Use {@link
1988     * #set(int,int) set(Calendar.HOUR_OF_DAY, 0)} to reset the hour
1989     * value.
1990     *
1991     * @param field the calendar field to be cleared.
1992     * @see #clear()
1993     */
1994    public final void clear(int field)
1995    {
1996        fields[field] = 0;
1997        stamp[field] = UNSET;
1998        isSet[field] = false;
1999
2000        areAllFieldsSet = areFieldsSet = false;
2001        isTimeSet = false;
2002    }
2003
2004    /**
2005     * Determines if the given calendar field has a value set,
2006     * including cases that the value has been set by internal fields
2007     * calculations triggered by a <code>get</code> method call.
2008     *
2009     * @param field the calendar field to test
2010     * @return <code>true</code> if the given calendar field has a value set;
2011     * <code>false</code> otherwise.
2012     */
2013    public final boolean isSet(int field)
2014    {
2015        return stamp[field] != UNSET;
2016    }
2017
2018    /**
2019     * Returns the string representation of the calendar
2020     * <code>field</code> value in the given <code>style</code> and
2021     * <code>locale</code>.  If no string representation is
2022     * applicable, <code>null</code> is returned. This method calls
2023     * {@link Calendar#get(int) get(field)} to get the calendar
2024     * <code>field</code> value if the string representation is
2025     * applicable to the given calendar <code>field</code>.
2026     *
2027     * <p>For example, if this <code>Calendar</code> is a
2028     * <code>GregorianCalendar</code> and its date is 2005-01-01, then
2029     * the string representation of the {@link #MONTH} field would be
2030     * "January" in the long style in an English locale or "Jan" in
2031     * the short style. However, no string representation would be
2032     * available for the {@link #DAY_OF_MONTH} field, and this method
2033     * would return <code>null</code>.
2034     *
2035     * <p>The default implementation supports the calendar fields for
2036     * which a {@link DateFormatSymbols} has names in the given
2037     * <code>locale</code>.
2038     *
2039     * @param field
2040     *        the calendar field for which the string representation
2041     *        is returned
2042     * @param style
2043     *        the style applied to the string representation; one of {@link
2044     *        #SHORT_FORMAT} ({@link #SHORT}), {@link #SHORT_STANDALONE},
2045     *        {@link #LONG_FORMAT} ({@link #LONG}), {@link #LONG_STANDALONE},
2046     *        {@link #NARROW_FORMAT}, or {@link #NARROW_STANDALONE}.
2047     * @param locale
2048     *        the locale for the string representation
2049     *        (any calendar types specified by {@code locale} are ignored)
2050     * @return the string representation of the given
2051     *        {@code field} in the given {@code style}, or
2052     *        {@code null} if no string representation is
2053     *        applicable.
2054     * @exception IllegalArgumentException
2055     *        if {@code field} or {@code style} is invalid,
2056     *        or if this {@code Calendar} is non-lenient and any
2057     *        of the calendar fields have invalid values
2058     * @exception NullPointerException
2059     *        if {@code locale} is null
2060     * @since 1.6
2061     */
2062    public String getDisplayName(int field, int style, Locale locale) {
2063        // BEGIN Android-changed: Treat ALL_STYLES as SHORT
2064        // Android has traditionally treated ALL_STYLES as SHORT, even though
2065        // it's not documented to be a valid value for style.
2066        if (style == ALL_STYLES) {
2067            style = SHORT;
2068        }
2069        // END Android-changed: Treat ALL_STYLES as SHORT
2070        if (!checkDisplayNameParams(field, style, SHORT, NARROW_FORMAT, locale,
2071                            ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
2072            return null;
2073        }
2074
2075        String calendarType = getCalendarType();
2076        int fieldValue = get(field);
2077        // the standalone and narrow styles are supported only through CalendarDataProviders.
2078        if (isStandaloneStyle(style) || isNarrowFormatStyle(style)) {
2079            String val = CalendarDataUtility.retrieveFieldValueName(calendarType,
2080                                                                    field, fieldValue,
2081                                                                    style, locale);
2082            // Perform fallback here to follow the CLDR rules
2083            if (val == null) {
2084                if (isNarrowFormatStyle(style)) {
2085                    val = CalendarDataUtility.retrieveFieldValueName(calendarType,
2086                                                                     field, fieldValue,
2087                                                                     toStandaloneStyle(style),
2088                                                                     locale);
2089                } else if (isStandaloneStyle(style)) {
2090                    val = CalendarDataUtility.retrieveFieldValueName(calendarType,
2091                                                                     field, fieldValue,
2092                                                                     getBaseStyle(style),
2093                                                                     locale);
2094                }
2095            }
2096            return val;
2097        }
2098
2099        DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
2100        String[] strings = getFieldStrings(field, style, symbols);
2101        if (strings != null) {
2102            if (fieldValue < strings.length) {
2103                return strings[fieldValue];
2104            }
2105        }
2106        return null;
2107    }
2108
2109    /**
2110     * Returns a {@code Map} containing all names of the calendar
2111     * {@code field} in the given {@code style} and
2112     * {@code locale} and their corresponding field values. For
2113     * example, if this {@code Calendar} is a {@link
2114     * GregorianCalendar}, the returned map would contain "Jan" to
2115     * {@link #JANUARY}, "Feb" to {@link #FEBRUARY}, and so on, in the
2116     * {@linkplain #SHORT short} style in an English locale.
2117     *
2118     * <p>Narrow names may not be unique due to use of single characters,
2119     * such as "S" for Sunday and Saturday. In that case narrow names are not
2120     * included in the returned {@code Map}.
2121     *
2122     * <p>The values of other calendar fields may be taken into
2123     * account to determine a set of display names. For example, if
2124     * this {@code Calendar} is a lunisolar calendar system and
2125     * the year value given by the {@link #YEAR} field has a leap
2126     * month, this method would return month names containing the leap
2127     * month name, and month names are mapped to their values specific
2128     * for the year.
2129     *
2130     * <p>The default implementation supports display names contained in
2131     * a {@link DateFormatSymbols}. For example, if {@code field}
2132     * is {@link #MONTH} and {@code style} is {@link
2133     * #ALL_STYLES}, this method returns a {@code Map} containing
2134     * all strings returned by {@link DateFormatSymbols#getShortMonths()}
2135     * and {@link DateFormatSymbols#getMonths()}.
2136     *
2137     * @param field
2138     *        the calendar field for which the display names are returned
2139     * @param style
2140     *        the style applied to the string representation; one of {@link
2141     *        #SHORT_FORMAT} ({@link #SHORT}), {@link #SHORT_STANDALONE},
2142     *        {@link #LONG_FORMAT} ({@link #LONG}), {@link #LONG_STANDALONE},
2143     *        {@link #NARROW_FORMAT}, or {@link #NARROW_STANDALONE}
2144     * @param locale
2145     *        the locale for the display names
2146     * @return a {@code Map} containing all display names in
2147     *        {@code style} and {@code locale} and their
2148     *        field values, or {@code null} if no display names
2149     *        are defined for {@code field}
2150     * @exception IllegalArgumentException
2151     *        if {@code field} or {@code style} is invalid,
2152     *        or if this {@code Calendar} is non-lenient and any
2153     *        of the calendar fields have invalid values
2154     * @exception NullPointerException
2155     *        if {@code locale} is null
2156     * @since 1.6
2157     */
2158    public Map<String, Integer> getDisplayNames(int field, int style, Locale locale) {
2159        if (!checkDisplayNameParams(field, style, ALL_STYLES, NARROW_FORMAT, locale,
2160                                    ERA_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
2161            return null;
2162        }
2163        // Android-added: Add complete() here to fix leniency, see http://b/35382060
2164        complete();
2165
2166        String calendarType = getCalendarType();
2167        if (style == ALL_STYLES || isStandaloneStyle(style) || isNarrowFormatStyle(style)) {
2168            Map<String, Integer> map;
2169            map = CalendarDataUtility.retrieveFieldValueNames(calendarType, field, style, locale);
2170
2171            // Perform fallback here to follow the CLDR rules
2172            if (map == null) {
2173                if (isNarrowFormatStyle(style)) {
2174                    map = CalendarDataUtility.retrieveFieldValueNames(calendarType, field,
2175                                                                      toStandaloneStyle(style), locale);
2176                } else if (style != ALL_STYLES) {
2177                    map = CalendarDataUtility.retrieveFieldValueNames(calendarType, field,
2178                                                                      getBaseStyle(style), locale);
2179                }
2180            }
2181            return map;
2182        }
2183
2184        // SHORT or LONG
2185        return getDisplayNamesImpl(field, style, locale);
2186    }
2187
2188    private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) {
2189        DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
2190        String[] strings = getFieldStrings(field, style, symbols);
2191        if (strings != null) {
2192            Map<String,Integer> names = new HashMap<>();
2193            for (int i = 0; i < strings.length; i++) {
2194                if (strings[i].length() == 0) {
2195                    continue;
2196                }
2197                names.put(strings[i], i);
2198            }
2199            return names;
2200        }
2201        return null;
2202    }
2203
2204    boolean checkDisplayNameParams(int field, int style, int minStyle, int maxStyle,
2205                                   Locale locale, int fieldMask) {
2206        int baseStyle = getBaseStyle(style); // Ignore the standalone mask
2207        if (field < 0 || field >= fields.length ||
2208            baseStyle < minStyle || baseStyle > maxStyle) {
2209            throw new IllegalArgumentException();
2210        }
2211        // BEGIN Android-added: Check for invalid baseStyle == 3
2212        // 3 is not a valid base style (unlike 1, 2 and 4). Throw if used.
2213        if (baseStyle == 3) {
2214            throw new IllegalArgumentException();
2215        }
2216        // END Android-added: Check for invalid baseStyle == 3
2217        if (locale == null) {
2218            throw new NullPointerException();
2219        }
2220        return isFieldSet(fieldMask, field);
2221    }
2222
2223    private String[] getFieldStrings(int field, int style, DateFormatSymbols symbols) {
2224        int baseStyle = getBaseStyle(style); // ignore the standalone mask
2225
2226        // DateFormatSymbols doesn't support any narrow names.
2227        if (baseStyle == NARROW_FORMAT) {
2228            return null;
2229        }
2230
2231        String[] strings = null;
2232        switch (field) {
2233        case ERA:
2234            strings = symbols.getEras();
2235            break;
2236
2237        case MONTH:
2238            strings = (baseStyle == LONG) ? symbols.getMonths() : symbols.getShortMonths();
2239            break;
2240
2241        case DAY_OF_WEEK:
2242            strings = (baseStyle == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays();
2243            break;
2244
2245        case AM_PM:
2246            strings = symbols.getAmPmStrings();
2247            break;
2248        }
2249        return strings;
2250    }
2251
2252    /**
2253     * Fills in any unset fields in the calendar fields. First, the {@link
2254     * #computeTime()} method is called if the time value (millisecond offset
2255     * from the <a href="#Epoch">Epoch</a>) has not been calculated from
2256     * calendar field values. Then, the {@link #computeFields()} method is
2257     * called to calculate all calendar field values.
2258     */
2259    protected void complete()
2260    {
2261        if (!isTimeSet) {
2262            updateTime();
2263        }
2264        if (!areFieldsSet || !areAllFieldsSet) {
2265            computeFields(); // fills in unset fields
2266            areAllFieldsSet = areFieldsSet = true;
2267        }
2268    }
2269
2270    /**
2271     * Returns whether the value of the specified calendar field has been set
2272     * externally by calling one of the setter methods rather than by the
2273     * internal time calculation.
2274     *
2275     * @return <code>true</code> if the field has been set externally,
2276     * <code>false</code> otherwise.
2277     * @exception IndexOutOfBoundsException if the specified
2278     *                <code>field</code> is out of range
2279     *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
2280     * @see #selectFields()
2281     * @see #setFieldsComputed(int)
2282     */
2283    final boolean isExternallySet(int field) {
2284        return stamp[field] >= MINIMUM_USER_STAMP;
2285    }
2286
2287    /**
2288     * Returns a field mask (bit mask) indicating all calendar fields that
2289     * have the state of externally or internally set.
2290     *
2291     * @return a bit mask indicating set state fields
2292     */
2293    final int getSetStateFields() {
2294        int mask = 0;
2295        for (int i = 0; i < fields.length; i++) {
2296            if (stamp[i] != UNSET) {
2297                mask |= 1 << i;
2298            }
2299        }
2300        return mask;
2301    }
2302
2303    /**
2304     * Sets the state of the specified calendar fields to
2305     * <em>computed</em>. This state means that the specified calendar fields
2306     * have valid values that have been set by internal time calculation
2307     * rather than by calling one of the setter methods.
2308     *
2309     * @param fieldMask the field to be marked as computed.
2310     * @exception IndexOutOfBoundsException if the specified
2311     *                <code>field</code> is out of range
2312     *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
2313     * @see #isExternallySet(int)
2314     * @see #selectFields()
2315     */
2316    final void setFieldsComputed(int fieldMask) {
2317        if (fieldMask == ALL_FIELDS) {
2318            for (int i = 0; i < fields.length; i++) {
2319                stamp[i] = COMPUTED;
2320                isSet[i] = true;
2321            }
2322            areFieldsSet = areAllFieldsSet = true;
2323        } else {
2324            for (int i = 0; i < fields.length; i++) {
2325                if ((fieldMask & 1) == 1) {
2326                    stamp[i] = COMPUTED;
2327                    isSet[i] = true;
2328                } else {
2329                    if (areAllFieldsSet && !isSet[i]) {
2330                        areAllFieldsSet = false;
2331                    }
2332                }
2333                fieldMask >>>= 1;
2334            }
2335        }
2336    }
2337
2338    /**
2339     * Sets the state of the calendar fields that are <em>not</em> specified
2340     * by <code>fieldMask</code> to <em>unset</em>. If <code>fieldMask</code>
2341     * specifies all the calendar fields, then the state of this
2342     * <code>Calendar</code> becomes that all the calendar fields are in sync
2343     * with the time value (millisecond offset from the Epoch).
2344     *
2345     * @param fieldMask the field mask indicating which calendar fields are in
2346     * sync with the time value.
2347     * @exception IndexOutOfBoundsException if the specified
2348     *                <code>field</code> is out of range
2349     *               (<code>field &lt; 0 || field &gt;= FIELD_COUNT</code>).
2350     * @see #isExternallySet(int)
2351     * @see #selectFields()
2352     */
2353    final void setFieldsNormalized(int fieldMask) {
2354        if (fieldMask != ALL_FIELDS) {
2355            for (int i = 0; i < fields.length; i++) {
2356                if ((fieldMask & 1) == 0) {
2357                    stamp[i] = fields[i] = 0; // UNSET == 0
2358                    isSet[i] = false;
2359                }
2360                fieldMask >>= 1;
2361            }
2362        }
2363
2364        // Some or all of the fields are in sync with the
2365        // milliseconds, but the stamp values are not normalized yet.
2366        areFieldsSet = true;
2367        areAllFieldsSet = false;
2368    }
2369
2370    /**
2371     * Returns whether the calendar fields are partially in sync with the time
2372     * value or fully in sync but not stamp values are not normalized yet.
2373     */
2374    final boolean isPartiallyNormalized() {
2375        return areFieldsSet && !areAllFieldsSet;
2376    }
2377
2378    /**
2379     * Returns whether the calendar fields are fully in sync with the time
2380     * value.
2381     */
2382    final boolean isFullyNormalized() {
2383        return areFieldsSet && areAllFieldsSet;
2384    }
2385
2386    /**
2387     * Marks this Calendar as not sync'd.
2388     */
2389    final void setUnnormalized() {
2390        areFieldsSet = areAllFieldsSet = false;
2391    }
2392
2393    /**
2394     * Returns whether the specified <code>field</code> is on in the
2395     * <code>fieldMask</code>.
2396     */
2397    static boolean isFieldSet(int fieldMask, int field) {
2398        return (fieldMask & (1 << field)) != 0;
2399    }
2400
2401    /**
2402     * Returns a field mask indicating which calendar field values
2403     * to be used to calculate the time value. The calendar fields are
2404     * returned as a bit mask, each bit of which corresponds to a field, i.e.,
2405     * the mask value of <code>field</code> is <code>(1 &lt;&lt;
2406     * field)</code>. For example, 0x26 represents the <code>YEAR</code>,
2407     * <code>MONTH</code>, and <code>DAY_OF_MONTH</code> fields (i.e., 0x26 is
2408     * equal to
2409     * <code>(1&lt;&lt;YEAR)|(1&lt;&lt;MONTH)|(1&lt;&lt;DAY_OF_MONTH))</code>.
2410     *
2411     * <p>This method supports the calendar fields resolution as described in
2412     * the class description. If the bit mask for a given field is on and its
2413     * field has not been set (i.e., <code>isSet(field)</code> is
2414     * <code>false</code>), then the default value of the field has to be
2415     * used, which case means that the field has been selected because the
2416     * selected combination involves the field.
2417     *
2418     * @return a bit mask of selected fields
2419     * @see #isExternallySet(int)
2420     */
2421    final int selectFields() {
2422        // This implementation has been taken from the GregorianCalendar class.
2423
2424        // The YEAR field must always be used regardless of its SET
2425        // state because YEAR is a mandatory field to determine the date
2426        // and the default value (EPOCH_YEAR) may change through the
2427        // normalization process.
2428        int fieldMask = YEAR_MASK;
2429
2430        if (stamp[ERA] != UNSET) {
2431            fieldMask |= ERA_MASK;
2432        }
2433        // Find the most recent group of fields specifying the day within
2434        // the year.  These may be any of the following combinations:
2435        //   MONTH + DAY_OF_MONTH
2436        //   MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
2437        //   MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
2438        //   DAY_OF_YEAR
2439        //   WEEK_OF_YEAR + DAY_OF_WEEK
2440        // We look for the most recent of the fields in each group to determine
2441        // the age of the group.  For groups involving a week-related field such
2442        // as WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR, both the
2443        // week-related field and the DAY_OF_WEEK must be set for the group as a
2444        // whole to be considered.  (See bug 4153860 - liu 7/24/98.)
2445        int dowStamp = stamp[DAY_OF_WEEK];
2446        int monthStamp = stamp[MONTH];
2447        int domStamp = stamp[DAY_OF_MONTH];
2448        int womStamp = aggregateStamp(stamp[WEEK_OF_MONTH], dowStamp);
2449        int dowimStamp = aggregateStamp(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
2450        int doyStamp = stamp[DAY_OF_YEAR];
2451        int woyStamp = aggregateStamp(stamp[WEEK_OF_YEAR], dowStamp);
2452
2453        int bestStamp = domStamp;
2454        if (womStamp > bestStamp) {
2455            bestStamp = womStamp;
2456        }
2457        if (dowimStamp > bestStamp) {
2458            bestStamp = dowimStamp;
2459        }
2460        if (doyStamp > bestStamp) {
2461            bestStamp = doyStamp;
2462        }
2463        if (woyStamp > bestStamp) {
2464            bestStamp = woyStamp;
2465        }
2466
2467        /* No complete combination exists.  Look for WEEK_OF_MONTH,
2468         * DAY_OF_WEEK_IN_MONTH, or WEEK_OF_YEAR alone.  Treat DAY_OF_WEEK alone
2469         * as DAY_OF_WEEK_IN_MONTH.
2470         */
2471        if (bestStamp == UNSET) {
2472            womStamp = stamp[WEEK_OF_MONTH];
2473            dowimStamp = Math.max(stamp[DAY_OF_WEEK_IN_MONTH], dowStamp);
2474            woyStamp = stamp[WEEK_OF_YEAR];
2475            bestStamp = Math.max(Math.max(womStamp, dowimStamp), woyStamp);
2476
2477            /* Treat MONTH alone or no fields at all as DAY_OF_MONTH.  This may
2478             * result in bestStamp = domStamp = UNSET if no fields are set,
2479             * which indicates DAY_OF_MONTH.
2480             */
2481            if (bestStamp == UNSET) {
2482                bestStamp = domStamp = monthStamp;
2483            }
2484        }
2485
2486        if (bestStamp == domStamp ||
2487           (bestStamp == womStamp && stamp[WEEK_OF_MONTH] >= stamp[WEEK_OF_YEAR]) ||
2488           (bestStamp == dowimStamp && stamp[DAY_OF_WEEK_IN_MONTH] >= stamp[WEEK_OF_YEAR])) {
2489            fieldMask |= MONTH_MASK;
2490            if (bestStamp == domStamp) {
2491                fieldMask |= DAY_OF_MONTH_MASK;
2492            } else {
2493                assert (bestStamp == womStamp || bestStamp == dowimStamp);
2494                if (dowStamp != UNSET) {
2495                    fieldMask |= DAY_OF_WEEK_MASK;
2496                }
2497                if (womStamp == dowimStamp) {
2498                    // When they are equal, give the priority to
2499                    // WEEK_OF_MONTH for compatibility.
2500                    if (stamp[WEEK_OF_MONTH] >= stamp[DAY_OF_WEEK_IN_MONTH]) {
2501                        fieldMask |= WEEK_OF_MONTH_MASK;
2502                    } else {
2503                        fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
2504                    }
2505                } else {
2506                    if (bestStamp == womStamp) {
2507                        fieldMask |= WEEK_OF_MONTH_MASK;
2508                    } else {
2509                        assert (bestStamp == dowimStamp);
2510                        if (stamp[DAY_OF_WEEK_IN_MONTH] != UNSET) {
2511                            fieldMask |= DAY_OF_WEEK_IN_MONTH_MASK;
2512                        }
2513                    }
2514                }
2515            }
2516        } else {
2517            assert (bestStamp == doyStamp || bestStamp == woyStamp ||
2518                    bestStamp == UNSET);
2519            if (bestStamp == doyStamp) {
2520                fieldMask |= DAY_OF_YEAR_MASK;
2521            } else {
2522                assert (bestStamp == woyStamp);
2523                if (dowStamp != UNSET) {
2524                    fieldMask |= DAY_OF_WEEK_MASK;
2525                }
2526                fieldMask |= WEEK_OF_YEAR_MASK;
2527            }
2528        }
2529
2530        // Find the best set of fields specifying the time of day.  There
2531        // are only two possibilities here; the HOUR_OF_DAY or the
2532        // AM_PM and the HOUR.
2533        int hourOfDayStamp = stamp[HOUR_OF_DAY];
2534        int hourStamp = aggregateStamp(stamp[HOUR], stamp[AM_PM]);
2535        bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
2536
2537        // if bestStamp is still UNSET, then take HOUR or AM_PM. (See 4846659)
2538        if (bestStamp == UNSET) {
2539            bestStamp = Math.max(stamp[HOUR], stamp[AM_PM]);
2540        }
2541
2542        // Hours
2543        if (bestStamp != UNSET) {
2544            if (bestStamp == hourOfDayStamp) {
2545                fieldMask |= HOUR_OF_DAY_MASK;
2546            } else {
2547                fieldMask |= HOUR_MASK;
2548                if (stamp[AM_PM] != UNSET) {
2549                    fieldMask |= AM_PM_MASK;
2550                }
2551            }
2552        }
2553        if (stamp[MINUTE] != UNSET) {
2554            fieldMask |= MINUTE_MASK;
2555        }
2556        if (stamp[SECOND] != UNSET) {
2557            fieldMask |= SECOND_MASK;
2558        }
2559        if (stamp[MILLISECOND] != UNSET) {
2560            fieldMask |= MILLISECOND_MASK;
2561        }
2562        if (stamp[ZONE_OFFSET] >= MINIMUM_USER_STAMP) {
2563                fieldMask |= ZONE_OFFSET_MASK;
2564        }
2565        if (stamp[DST_OFFSET] >= MINIMUM_USER_STAMP) {
2566            fieldMask |= DST_OFFSET_MASK;
2567        }
2568
2569        return fieldMask;
2570    }
2571
2572    int getBaseStyle(int style) {
2573        return style & ~STANDALONE_MASK;
2574    }
2575
2576    private int toStandaloneStyle(int style) {
2577        return style | STANDALONE_MASK;
2578    }
2579
2580    private boolean isStandaloneStyle(int style) {
2581        return (style & STANDALONE_MASK) != 0;
2582    }
2583
2584    private boolean isNarrowStyle(int style) {
2585        return style == NARROW_FORMAT || style == NARROW_STANDALONE;
2586    }
2587
2588    private boolean isNarrowFormatStyle(int style) {
2589        return style == NARROW_FORMAT;
2590    }
2591
2592    /**
2593     * Returns the pseudo-time-stamp for two fields, given their
2594     * individual pseudo-time-stamps.  If either of the fields
2595     * is unset, then the aggregate is unset.  Otherwise, the
2596     * aggregate is the later of the two stamps.
2597     */
2598    private static int aggregateStamp(int stamp_a, int stamp_b) {
2599        if (stamp_a == UNSET || stamp_b == UNSET) {
2600            return UNSET;
2601        }
2602        return (stamp_a > stamp_b) ? stamp_a : stamp_b;
2603    }
2604
2605    /**
2606     * Returns an unmodifiable {@code Set} containing all calendar types
2607     * supported by {@code Calendar} in the runtime environment. The available
2608     * calendar types can be used for the <a
2609     * href="Locale.html#def_locale_extension">Unicode locale extensions</a>.
2610     * The {@code Set} returned contains at least {@code "gregory"}. The
2611     * calendar types don't include aliases, such as {@code "gregorian"} for
2612     * {@code "gregory"}.
2613     *
2614     * @return an unmodifiable {@code Set} containing all available calendar types
2615     * @since 1.8
2616     * @see #getCalendarType()
2617     * @see Calendar.Builder#setCalendarType(String)
2618     * @see Locale#getUnicodeLocaleType(String)
2619     */
2620    public static Set<String> getAvailableCalendarTypes() {
2621        return AvailableCalendarTypes.SET;
2622    }
2623
2624    private static class AvailableCalendarTypes {
2625        private static final Set<String> SET;
2626        static {
2627            Set<String> set = new HashSet<>(3);
2628            set.add("gregory");
2629            // Android-changed: removed "buddhist" and "japanese".
2630            SET = Collections.unmodifiableSet(set);
2631        }
2632        private AvailableCalendarTypes() {
2633        }
2634    }
2635
2636    /**
2637     * Returns the calendar type of this {@code Calendar}. Calendar types are
2638     * defined by the <em>Unicode Locale Data Markup Language (LDML)</em>
2639     * specification.
2640     *
2641     * <p>The default implementation of this method returns the class name of
2642     * this {@code Calendar} instance. Any subclasses that implement
2643     * LDML-defined calendar systems should override this method to return
2644     * appropriate calendar types.
2645     *
2646     * @return the LDML-defined calendar type or the class name of this
2647     *         {@code Calendar} instance
2648     * @since 1.8
2649     * @see <a href="Locale.html#def_extensions">Locale extensions</a>
2650     * @see Locale.Builder#setLocale(Locale)
2651     * @see Locale.Builder#setUnicodeLocaleKeyword(String, String)
2652     */
2653    public String getCalendarType() {
2654        return this.getClass().getName();
2655    }
2656
2657    /**
2658     * Compares this <code>Calendar</code> to the specified
2659     * <code>Object</code>.  The result is <code>true</code> if and only if
2660     * the argument is a <code>Calendar</code> object of the same calendar
2661     * system that represents the same time value (millisecond offset from the
2662     * <a href="#Epoch">Epoch</a>) under the same
2663     * <code>Calendar</code> parameters as this object.
2664     *
2665     * <p>The <code>Calendar</code> parameters are the values represented
2666     * by the <code>isLenient</code>, <code>getFirstDayOfWeek</code>,
2667     * <code>getMinimalDaysInFirstWeek</code> and <code>getTimeZone</code>
2668     * methods. If there is any difference in those parameters
2669     * between the two <code>Calendar</code>s, this method returns
2670     * <code>false</code>.
2671     *
2672     * <p>Use the {@link #compareTo(Calendar) compareTo} method to
2673     * compare only the time values.
2674     *
2675     * @param obj the object to compare with.
2676     * @return <code>true</code> if this object is equal to <code>obj</code>;
2677     * <code>false</code> otherwise.
2678     */
2679    @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
2680    @Override
2681    public boolean equals(Object obj) {
2682        if (this == obj) {
2683            return true;
2684        }
2685        try {
2686            Calendar that = (Calendar)obj;
2687            return compareTo(getMillisOf(that)) == 0 &&
2688                lenient == that.lenient &&
2689                firstDayOfWeek == that.firstDayOfWeek &&
2690                minimalDaysInFirstWeek == that.minimalDaysInFirstWeek &&
2691                zone.equals(that.zone);
2692        } catch (Exception e) {
2693            // Note: GregorianCalendar.computeTime throws
2694            // IllegalArgumentException if the ERA value is invalid
2695            // even it's in lenient mode.
2696        }
2697        return false;
2698    }
2699
2700    /**
2701     * Returns a hash code for this calendar.
2702     *
2703     * @return a hash code value for this object.
2704     * @since 1.2
2705     */
2706    @Override
2707    public int hashCode() {
2708        // 'otheritems' represents the hash code for the previous versions.
2709        int otheritems = (lenient ? 1 : 0)
2710            | (firstDayOfWeek << 1)
2711            | (minimalDaysInFirstWeek << 4)
2712            | (zone.hashCode() << 7);
2713        long t = getMillisOf(this);
2714        return (int) t ^ (int)(t >> 32) ^ otheritems;
2715    }
2716
2717    /**
2718     * Returns whether this <code>Calendar</code> represents a time
2719     * before the time represented by the specified
2720     * <code>Object</code>. This method is equivalent to:
2721     * <pre>{@code
2722     *         compareTo(when) < 0
2723     * }</pre>
2724     * if and only if <code>when</code> is a <code>Calendar</code>
2725     * instance. Otherwise, the method returns <code>false</code>.
2726     *
2727     * @param when the <code>Object</code> to be compared
2728     * @return <code>true</code> if the time of this
2729     * <code>Calendar</code> is before the time represented by
2730     * <code>when</code>; <code>false</code> otherwise.
2731     * @see     #compareTo(Calendar)
2732     */
2733    public boolean before(Object when) {
2734        return when instanceof Calendar
2735            && compareTo((Calendar)when) < 0;
2736    }
2737
2738    /**
2739     * Returns whether this <code>Calendar</code> represents a time
2740     * after the time represented by the specified
2741     * <code>Object</code>. This method is equivalent to:
2742     * <pre>{@code
2743     *         compareTo(when) > 0
2744     * }</pre>
2745     * if and only if <code>when</code> is a <code>Calendar</code>
2746     * instance. Otherwise, the method returns <code>false</code>.
2747     *
2748     * @param when the <code>Object</code> to be compared
2749     * @return <code>true</code> if the time of this <code>Calendar</code> is
2750     * after the time represented by <code>when</code>; <code>false</code>
2751     * otherwise.
2752     * @see     #compareTo(Calendar)
2753     */
2754    public boolean after(Object when) {
2755        return when instanceof Calendar
2756            && compareTo((Calendar)when) > 0;
2757    }
2758
2759    /**
2760     * Compares the time values (millisecond offsets from the <a
2761     * href="#Epoch">Epoch</a>) represented by two
2762     * <code>Calendar</code> objects.
2763     *
2764     * @param anotherCalendar the <code>Calendar</code> to be compared.
2765     * @return the value <code>0</code> if the time represented by the argument
2766     * is equal to the time represented by this <code>Calendar</code>; a value
2767     * less than <code>0</code> if the time of this <code>Calendar</code> is
2768     * before the time represented by the argument; and a value greater than
2769     * <code>0</code> if the time of this <code>Calendar</code> is after the
2770     * time represented by the argument.
2771     * @exception NullPointerException if the specified <code>Calendar</code> is
2772     *            <code>null</code>.
2773     * @exception IllegalArgumentException if the time value of the
2774     * specified <code>Calendar</code> object can't be obtained due to
2775     * any invalid calendar values.
2776     * @since   1.5
2777     */
2778    @Override
2779    public int compareTo(Calendar anotherCalendar) {
2780        return compareTo(getMillisOf(anotherCalendar));
2781    }
2782
2783    /**
2784     * Adds or subtracts the specified amount of time to the given calendar field,
2785     * based on the calendar's rules. For example, to subtract 5 days from
2786     * the current time of the calendar, you can achieve it by calling:
2787     * <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>.
2788     *
2789     * @param field the calendar field.
2790     * @param amount the amount of date or time to be added to the field.
2791     * @see #roll(int,int)
2792     * @see #set(int,int)
2793     */
2794    abstract public void add(int field, int amount);
2795
2796    /**
2797     * Adds or subtracts (up/down) a single unit of time on the given time
2798     * field without changing larger fields. For example, to roll the current
2799     * date up by one day, you can achieve it by calling:
2800     * <p>roll(Calendar.DATE, true).
2801     * When rolling on the year or Calendar.YEAR field, it will roll the year
2802     * value in the range between 1 and the value returned by calling
2803     * <code>getMaximum(Calendar.YEAR)</code>.
2804     * When rolling on the month or Calendar.MONTH field, other fields like
2805     * date might conflict and, need to be changed. For instance,
2806     * rolling the month on the date 01/31/96 will result in 02/29/96.
2807     * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will
2808     * roll the hour value in the range between 0 and 23, which is zero-based.
2809     *
2810     * @param field the time field.
2811     * @param up indicates if the value of the specified time field is to be
2812     * rolled up or rolled down. Use true if rolling up, false otherwise.
2813     * @see Calendar#add(int,int)
2814     * @see Calendar#set(int,int)
2815     */
2816    abstract public void roll(int field, boolean up);
2817
2818    /**
2819     * Adds the specified (signed) amount to the specified calendar field
2820     * without changing larger fields.  A negative amount means to roll
2821     * down.
2822     *
2823     * <p>NOTE:  This default implementation on <code>Calendar</code> just repeatedly calls the
2824     * version of {@link #roll(int,boolean) roll()} that rolls by one unit.  This may not
2825     * always do the right thing.  For example, if the <code>DAY_OF_MONTH</code> field is 31,
2826     * rolling through February will leave it set to 28.  The <code>GregorianCalendar</code>
2827     * version of this function takes care of this problem.  Other subclasses
2828     * should also provide overrides of this function that do the right thing.
2829     *
2830     * @param field the calendar field.
2831     * @param amount the signed amount to add to the calendar <code>field</code>.
2832     * @since 1.2
2833     * @see #roll(int,boolean)
2834     * @see #add(int,int)
2835     * @see #set(int,int)
2836     */
2837    public void roll(int field, int amount)
2838    {
2839        while (amount > 0) {
2840            roll(field, true);
2841            amount--;
2842        }
2843        while (amount < 0) {
2844            roll(field, false);
2845            amount++;
2846        }
2847    }
2848
2849    /**
2850     * Sets the time zone with the given time zone value.
2851     *
2852     * @param value the given time zone.
2853     */
2854    public void setTimeZone(TimeZone value)
2855    {
2856        zone = value;
2857        sharedZone = false;
2858        /* Recompute the fields from the time using the new zone.  This also
2859         * works if isTimeSet is false (after a call to set()).  In that case
2860         * the time will be computed from the fields using the new zone, then
2861         * the fields will get recomputed from that.  Consider the sequence of
2862         * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
2863         * Is cal set to 1 o'clock EST or 1 o'clock PST?  Answer: PST.  More
2864         * generally, a call to setTimeZone() affects calls to set() BEFORE AND
2865         * AFTER it up to the next call to complete().
2866         */
2867        areAllFieldsSet = areFieldsSet = false;
2868    }
2869
2870    /**
2871     * Gets the time zone.
2872     *
2873     * @return the time zone object associated with this calendar.
2874     */
2875    public TimeZone getTimeZone()
2876    {
2877        // If the TimeZone object is shared by other Calendar instances, then
2878        // create a clone.
2879        if (sharedZone) {
2880            zone = (TimeZone) zone.clone();
2881            sharedZone = false;
2882        }
2883        return zone;
2884    }
2885
2886    /**
2887     * Returns the time zone (without cloning).
2888     */
2889    TimeZone getZone() {
2890        return zone;
2891    }
2892
2893    /**
2894     * Sets the sharedZone flag to <code>shared</code>.
2895     */
2896    void setZoneShared(boolean shared) {
2897        sharedZone = shared;
2898    }
2899
2900    /**
2901     * Specifies whether or not date/time interpretation is to be lenient.  With
2902     * lenient interpretation, a date such as "February 942, 1996" will be
2903     * treated as being equivalent to the 941st day after February 1, 1996.
2904     * With strict (non-lenient) interpretation, such dates will cause an exception to be
2905     * thrown. The default is lenient.
2906     *
2907     * @param lenient <code>true</code> if the lenient mode is to be turned
2908     * on; <code>false</code> if it is to be turned off.
2909     * @see #isLenient()
2910     * @see java.text.DateFormat#setLenient
2911     */
2912    public void setLenient(boolean lenient)
2913    {
2914        this.lenient = lenient;
2915    }
2916
2917    /**
2918     * Tells whether date/time interpretation is to be lenient.
2919     *
2920     * @return <code>true</code> if the interpretation mode of this calendar is lenient;
2921     * <code>false</code> otherwise.
2922     * @see #setLenient(boolean)
2923     */
2924    public boolean isLenient()
2925    {
2926        return lenient;
2927    }
2928
2929    /**
2930     * Sets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
2931     * <code>MONDAY</code> in France.
2932     *
2933     * @param value the given first day of the week.
2934     * @see #getFirstDayOfWeek()
2935     * @see #getMinimalDaysInFirstWeek()
2936     */
2937    public void setFirstDayOfWeek(int value)
2938    {
2939        if (firstDayOfWeek == value) {
2940            return;
2941        }
2942        firstDayOfWeek = value;
2943        invalidateWeekFields();
2944    }
2945
2946    /**
2947     * Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
2948     * <code>MONDAY</code> in France.
2949     *
2950     * @return the first day of the week.
2951     * @see #setFirstDayOfWeek(int)
2952     * @see #getMinimalDaysInFirstWeek()
2953     */
2954    public int getFirstDayOfWeek()
2955    {
2956        return firstDayOfWeek;
2957    }
2958
2959    /**
2960     * Sets what the minimal days required in the first week of the year are;
2961     * For example, if the first week is defined as one that contains the first
2962     * day of the first month of a year, call this method with value 1. If it
2963     * must be a full week, use value 7.
2964     *
2965     * @param value the given minimal days required in the first week
2966     * of the year.
2967     * @see #getMinimalDaysInFirstWeek()
2968     */
2969    public void setMinimalDaysInFirstWeek(int value)
2970    {
2971        if (minimalDaysInFirstWeek == value) {
2972            return;
2973        }
2974        minimalDaysInFirstWeek = value;
2975        invalidateWeekFields();
2976    }
2977
2978    /**
2979     * Gets what the minimal days required in the first week of the year are;
2980     * e.g., if the first week is defined as one that contains the first day
2981     * of the first month of a year, this method returns 1. If
2982     * the minimal days required must be a full week, this method
2983     * returns 7.
2984     *
2985     * @return the minimal days required in the first week of the year.
2986     * @see #setMinimalDaysInFirstWeek(int)
2987     */
2988    public int getMinimalDaysInFirstWeek()
2989    {
2990        return minimalDaysInFirstWeek;
2991    }
2992
2993    /**
2994     * Returns whether this {@code Calendar} supports week dates.
2995     *
2996     * <p>The default implementation of this method returns {@code false}.
2997     *
2998     * @return {@code true} if this {@code Calendar} supports week dates;
2999     *         {@code false} otherwise.
3000     * @see #getWeekYear()
3001     * @see #setWeekDate(int,int,int)
3002     * @see #getWeeksInWeekYear()
3003     * @since 1.7
3004     */
3005    public boolean isWeekDateSupported() {
3006        return false;
3007    }
3008
3009    /**
3010     * Returns the week year represented by this {@code Calendar}. The
3011     * week year is in sync with the week cycle. The {@linkplain
3012     * #getFirstDayOfWeek() first day of the first week} is the first
3013     * day of the week year.
3014     *
3015     * <p>The default implementation of this method throws an
3016     * {@link UnsupportedOperationException}.
3017     *
3018     * @return the week year of this {@code Calendar}
3019     * @exception UnsupportedOperationException
3020     *            if any week year numbering isn't supported
3021     *            in this {@code Calendar}.
3022     * @see #isWeekDateSupported()
3023     * @see #getFirstDayOfWeek()
3024     * @see #getMinimalDaysInFirstWeek()
3025     * @since 1.7
3026     */
3027    public int getWeekYear() {
3028        throw new UnsupportedOperationException();
3029    }
3030
3031    /**
3032     * Sets the date of this {@code Calendar} with the the given date
3033     * specifiers - week year, week of year, and day of week.
3034     *
3035     * <p>Unlike the {@code set} method, all of the calendar fields
3036     * and {@code time} values are calculated upon return.
3037     *
3038     * <p>If {@code weekOfYear} is out of the valid week-of-year range
3039     * in {@code weekYear}, the {@code weekYear} and {@code
3040     * weekOfYear} values are adjusted in lenient mode, or an {@code
3041     * IllegalArgumentException} is thrown in non-lenient mode.
3042     *
3043     * <p>The default implementation of this method throws an
3044     * {@code UnsupportedOperationException}.
3045     *
3046     * @param weekYear   the week year
3047     * @param weekOfYear the week number based on {@code weekYear}
3048     * @param dayOfWeek  the day of week value: one of the constants
3049     *                   for the {@link #DAY_OF_WEEK} field: {@link
3050     *                   #SUNDAY}, ..., {@link #SATURDAY}.
3051     * @exception IllegalArgumentException
3052     *            if any of the given date specifiers is invalid
3053     *            or any of the calendar fields are inconsistent
3054     *            with the given date specifiers in non-lenient mode
3055     * @exception UnsupportedOperationException
3056     *            if any week year numbering isn't supported in this
3057     *            {@code Calendar}.
3058     * @see #isWeekDateSupported()
3059     * @see #getFirstDayOfWeek()
3060     * @see #getMinimalDaysInFirstWeek()
3061     * @since 1.7
3062     */
3063    public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
3064        throw new UnsupportedOperationException();
3065    }
3066
3067    /**
3068     * Returns the number of weeks in the week year represented by this
3069     * {@code Calendar}.
3070     *
3071     * <p>The default implementation of this method throws an
3072     * {@code UnsupportedOperationException}.
3073     *
3074     * @return the number of weeks in the week year.
3075     * @exception UnsupportedOperationException
3076     *            if any week year numbering isn't supported in this
3077     *            {@code Calendar}.
3078     * @see #WEEK_OF_YEAR
3079     * @see #isWeekDateSupported()
3080     * @see #getWeekYear()
3081     * @see #getActualMaximum(int)
3082     * @since 1.7
3083     */
3084    public int getWeeksInWeekYear() {
3085        throw new UnsupportedOperationException();
3086    }
3087
3088    /**
3089     * Returns the minimum value for the given calendar field of this
3090     * <code>Calendar</code> instance. The minimum value is defined as
3091     * the smallest value returned by the {@link #get(int) get} method
3092     * for any possible time value.  The minimum value depends on
3093     * calendar system specific parameters of the instance.
3094     *
3095     * @param field the calendar field.
3096     * @return the minimum value for the given calendar field.
3097     * @see #getMaximum(int)
3098     * @see #getGreatestMinimum(int)
3099     * @see #getLeastMaximum(int)
3100     * @see #getActualMinimum(int)
3101     * @see #getActualMaximum(int)
3102     */
3103    abstract public int getMinimum(int field);
3104
3105    /**
3106     * Returns the maximum value for the given calendar field of this
3107     * <code>Calendar</code> instance. The maximum value is defined as
3108     * the largest value returned by the {@link #get(int) get} method
3109     * for any possible time value. The maximum value depends on
3110     * calendar system specific parameters of the instance.
3111     *
3112     * @param field the calendar field.
3113     * @return the maximum value for the given calendar field.
3114     * @see #getMinimum(int)
3115     * @see #getGreatestMinimum(int)
3116     * @see #getLeastMaximum(int)
3117     * @see #getActualMinimum(int)
3118     * @see #getActualMaximum(int)
3119     */
3120    abstract public int getMaximum(int field);
3121
3122    /**
3123     * Returns the highest minimum value for the given calendar field
3124     * of this <code>Calendar</code> instance. The highest minimum
3125     * value is defined as the largest value returned by {@link
3126     * #getActualMinimum(int)} for any possible time value. The
3127     * greatest minimum value depends on calendar system specific
3128     * parameters of the instance.
3129     *
3130     * @param field the calendar field.
3131     * @return the highest minimum value for the given calendar field.
3132     * @see #getMinimum(int)
3133     * @see #getMaximum(int)
3134     * @see #getLeastMaximum(int)
3135     * @see #getActualMinimum(int)
3136     * @see #getActualMaximum(int)
3137     */
3138    abstract public int getGreatestMinimum(int field);
3139
3140    /**
3141     * Returns the lowest maximum value for the given calendar field
3142     * of this <code>Calendar</code> instance. The lowest maximum
3143     * value is defined as the smallest value returned by {@link
3144     * #getActualMaximum(int)} for any possible time value. The least
3145     * maximum value depends on calendar system specific parameters of
3146     * the instance. For example, a <code>Calendar</code> for the
3147     * Gregorian calendar system returns 28 for the
3148     * <code>DAY_OF_MONTH</code> field, because the 28th is the last
3149     * day of the shortest month of this calendar, February in a
3150     * common year.
3151     *
3152     * @param field the calendar field.
3153     * @return the lowest maximum value for the given calendar field.
3154     * @see #getMinimum(int)
3155     * @see #getMaximum(int)
3156     * @see #getGreatestMinimum(int)
3157     * @see #getActualMinimum(int)
3158     * @see #getActualMaximum(int)
3159     */
3160    abstract public int getLeastMaximum(int field);
3161
3162    /**
3163     * Returns the minimum value that the specified calendar field
3164     * could have, given the time value of this <code>Calendar</code>.
3165     *
3166     * <p>The default implementation of this method uses an iterative
3167     * algorithm to determine the actual minimum value for the
3168     * calendar field. Subclasses should, if possible, override this
3169     * with a more efficient implementation - in many cases, they can
3170     * simply return <code>getMinimum()</code>.
3171     *
3172     * @param field the calendar field
3173     * @return the minimum of the given calendar field for the time
3174     * value of this <code>Calendar</code>
3175     * @see #getMinimum(int)
3176     * @see #getMaximum(int)
3177     * @see #getGreatestMinimum(int)
3178     * @see #getLeastMaximum(int)
3179     * @see #getActualMaximum(int)
3180     * @since 1.2
3181     */
3182    public int getActualMinimum(int field) {
3183        int fieldValue = getGreatestMinimum(field);
3184        int endValue = getMinimum(field);
3185
3186        // if we know that the minimum value is always the same, just return it
3187        if (fieldValue == endValue) {
3188            return fieldValue;
3189        }
3190
3191        // clone the calendar so we don't mess with the real one, and set it to
3192        // accept anything for the field values
3193        Calendar work = (Calendar)this.clone();
3194        work.setLenient(true);
3195
3196        // now try each value from getLeastMaximum() to getMaximum() one by one until
3197        // we get a value that normalizes to another value.  The last value that
3198        // normalizes to itself is the actual minimum for the current date
3199        int result = fieldValue;
3200
3201        do {
3202            work.set(field, fieldValue);
3203            if (work.get(field) != fieldValue) {
3204                break;
3205            } else {
3206                result = fieldValue;
3207                fieldValue--;
3208            }
3209        } while (fieldValue >= endValue);
3210
3211        return result;
3212    }
3213
3214    /**
3215     * Returns the maximum value that the specified calendar field
3216     * could have, given the time value of this
3217     * <code>Calendar</code>. For example, the actual maximum value of
3218     * the <code>MONTH</code> field is 12 in some years, and 13 in
3219     * other years in the Hebrew calendar system.
3220     *
3221     * <p>The default implementation of this method uses an iterative
3222     * algorithm to determine the actual maximum value for the
3223     * calendar field. Subclasses should, if possible, override this
3224     * with a more efficient implementation.
3225     *
3226     * @param field the calendar field
3227     * @return the maximum of the given calendar field for the time
3228     * value of this <code>Calendar</code>
3229     * @see #getMinimum(int)
3230     * @see #getMaximum(int)
3231     * @see #getGreatestMinimum(int)
3232     * @see #getLeastMaximum(int)
3233     * @see #getActualMinimum(int)
3234     * @since 1.2
3235     */
3236    public int getActualMaximum(int field) {
3237        int fieldValue = getLeastMaximum(field);
3238        int endValue = getMaximum(field);
3239
3240        // if we know that the maximum value is always the same, just return it.
3241        if (fieldValue == endValue) {
3242            return fieldValue;
3243        }
3244
3245        // clone the calendar so we don't mess with the real one, and set it to
3246        // accept anything for the field values.
3247        Calendar work = (Calendar)this.clone();
3248        work.setLenient(true);
3249
3250        // if we're counting weeks, set the day of the week to Sunday.  We know the
3251        // last week of a month or year will contain the first day of the week.
3252        if (field == WEEK_OF_YEAR || field == WEEK_OF_MONTH) {
3253            work.set(DAY_OF_WEEK, firstDayOfWeek);
3254        }
3255
3256        // now try each value from getLeastMaximum() to getMaximum() one by one until
3257        // we get a value that normalizes to another value.  The last value that
3258        // normalizes to itself is the actual maximum for the current date
3259        int result = fieldValue;
3260
3261        do {
3262            work.set(field, fieldValue);
3263            if (work.get(field) != fieldValue) {
3264                break;
3265            } else {
3266                result = fieldValue;
3267                fieldValue++;
3268            }
3269        } while (fieldValue <= endValue);
3270
3271        return result;
3272    }
3273
3274    /**
3275     * Creates and returns a copy of this object.
3276     *
3277     * @return a copy of this object.
3278     */
3279    @Override
3280    public Object clone()
3281    {
3282        try {
3283            Calendar other = (Calendar) super.clone();
3284
3285            other.fields = new int[FIELD_COUNT];
3286            other.isSet = new boolean[FIELD_COUNT];
3287            other.stamp = new int[FIELD_COUNT];
3288            for (int i = 0; i < FIELD_COUNT; i++) {
3289                other.fields[i] = fields[i];
3290                other.stamp[i] = stamp[i];
3291                other.isSet[i] = isSet[i];
3292            }
3293            other.zone = (TimeZone) zone.clone();
3294            return other;
3295        }
3296        catch (CloneNotSupportedException e) {
3297            // this shouldn't happen, since we are Cloneable
3298            throw new InternalError(e);
3299        }
3300    }
3301
3302    private static final String[] FIELD_NAME = {
3303        "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH",
3304        "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR",
3305        "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET",
3306        "DST_OFFSET"
3307    };
3308
3309    /**
3310     * Returns the name of the specified calendar field.
3311     *
3312     * @param field the calendar field
3313     * @return the calendar field name
3314     * @exception IndexOutOfBoundsException if <code>field</code> is negative,
3315     * equal to or greater then <code>FIELD_COUNT</code>.
3316     */
3317    static String getFieldName(int field) {
3318        return FIELD_NAME[field];
3319    }
3320
3321    /**
3322     * Return a string representation of this calendar. This method
3323     * is intended to be used only for debugging purposes, and the
3324     * format of the returned string may vary between implementations.
3325     * The returned string may be empty but may not be <code>null</code>.
3326     *
3327     * @return  a string representation of this calendar.
3328     */
3329    @Override
3330    public String toString() {
3331        // NOTE: BuddhistCalendar.toString() interprets the string
3332        // produced by this method so that the Gregorian year number
3333        // is substituted by its B.E. year value. It relies on
3334        // "...,YEAR=<year>,..." or "...,YEAR=?,...".
3335        StringBuilder buffer = new StringBuilder(800);
3336        buffer.append(getClass().getName()).append('[');
3337        appendValue(buffer, "time", isTimeSet, time);
3338        buffer.append(",areFieldsSet=").append(areFieldsSet);
3339        buffer.append(",areAllFieldsSet=").append(areAllFieldsSet);
3340        buffer.append(",lenient=").append(lenient);
3341        buffer.append(",zone=").append(zone);
3342        appendValue(buffer, ",firstDayOfWeek", true, (long) firstDayOfWeek);
3343        appendValue(buffer, ",minimalDaysInFirstWeek", true, (long) minimalDaysInFirstWeek);
3344        for (int i = 0; i < FIELD_COUNT; ++i) {
3345            buffer.append(',');
3346            appendValue(buffer, FIELD_NAME[i], isSet(i), (long) fields[i]);
3347        }
3348        buffer.append(']');
3349        return buffer.toString();
3350    }
3351
3352    // =======================privates===============================
3353
3354    private static void appendValue(StringBuilder sb, String item, boolean valid, long value) {
3355        sb.append(item).append('=');
3356        if (valid) {
3357            sb.append(value);
3358        } else {
3359            sb.append('?');
3360        }
3361    }
3362
3363    /**
3364     * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.
3365     * They are used to figure out the week count for a specific date for
3366     * a given locale. These must be set when a Calendar is constructed.
3367     * @param desiredLocale the given locale.
3368     */
3369    private void setWeekCountData(Locale desiredLocale)
3370    {
3371        /* try to get the Locale data from the cache */
3372        int[] data = cachedLocaleData.get(desiredLocale);
3373        if (data == null) {  /* cache miss */
3374            // Android-changed: Use ICU4C to get week data.
3375            LocaleData localeData = LocaleData.get(desiredLocale);
3376            data = new int[2];
3377            data[0] = localeData.firstDayOfWeek.intValue();
3378            data[1] = localeData.minimalDaysInFirstWeek.intValue();
3379            cachedLocaleData.putIfAbsent(desiredLocale, data);
3380        }
3381        firstDayOfWeek = data[0];
3382        minimalDaysInFirstWeek = data[1];
3383    }
3384
3385    /**
3386     * Recomputes the time and updates the status fields isTimeSet
3387     * and areFieldsSet.  Callers should check isTimeSet and only
3388     * call this method if isTimeSet is false.
3389     */
3390    private void updateTime() {
3391        computeTime();
3392        // The areFieldsSet and areAllFieldsSet values are no longer
3393        // controlled here (as of 1.5).
3394        isTimeSet = true;
3395    }
3396
3397    private int compareTo(long t) {
3398        long thisTime = getMillisOf(this);
3399        return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
3400    }
3401
3402    private static long getMillisOf(Calendar calendar) {
3403        if (calendar.isTimeSet) {
3404            return calendar.time;
3405        }
3406        Calendar cal = (Calendar) calendar.clone();
3407        cal.setLenient(true);
3408        return cal.getTimeInMillis();
3409    }
3410
3411    /**
3412     * Adjusts the stamp[] values before nextStamp overflow. nextStamp
3413     * is set to the next stamp value upon the return.
3414     */
3415    private void adjustStamp() {
3416        int max = MINIMUM_USER_STAMP;
3417        int newStamp = MINIMUM_USER_STAMP;
3418
3419        for (;;) {
3420            int min = Integer.MAX_VALUE;
3421            for (int i = 0; i < stamp.length; i++) {
3422                int v = stamp[i];
3423                if (v >= newStamp && min > v) {
3424                    min = v;
3425                }
3426                if (max < v) {
3427                    max = v;
3428                }
3429            }
3430            if (max != min && min == Integer.MAX_VALUE) {
3431                break;
3432            }
3433            for (int i = 0; i < stamp.length; i++) {
3434                if (stamp[i] == min) {
3435                    stamp[i] = newStamp;
3436                }
3437            }
3438            newStamp++;
3439            if (min == max) {
3440                break;
3441            }
3442        }
3443        nextStamp = newStamp;
3444    }
3445
3446    /**
3447     * Sets the WEEK_OF_MONTH and WEEK_OF_YEAR fields to new values with the
3448     * new parameter value if they have been calculated internally.
3449     */
3450    private void invalidateWeekFields()
3451    {
3452        if (stamp[WEEK_OF_MONTH] != COMPUTED &&
3453            stamp[WEEK_OF_YEAR] != COMPUTED) {
3454            return;
3455        }
3456
3457        // We have to check the new values of these fields after changing
3458        // firstDayOfWeek and/or minimalDaysInFirstWeek. If the field values
3459        // have been changed, then set the new values. (4822110)
3460        Calendar cal = (Calendar) clone();
3461        cal.setLenient(true);
3462        cal.clear(WEEK_OF_MONTH);
3463        cal.clear(WEEK_OF_YEAR);
3464
3465        if (stamp[WEEK_OF_MONTH] == COMPUTED) {
3466            int weekOfMonth = cal.get(WEEK_OF_MONTH);
3467            if (fields[WEEK_OF_MONTH] != weekOfMonth) {
3468                fields[WEEK_OF_MONTH] = weekOfMonth;
3469            }
3470        }
3471
3472        if (stamp[WEEK_OF_YEAR] == COMPUTED) {
3473            int weekOfYear = cal.get(WEEK_OF_YEAR);
3474            if (fields[WEEK_OF_YEAR] != weekOfYear) {
3475                fields[WEEK_OF_YEAR] = weekOfYear;
3476            }
3477        }
3478    }
3479
3480    /**
3481     * Save the state of this object to a stream (i.e., serialize it).
3482     *
3483     * Ideally, <code>Calendar</code> would only write out its state data and
3484     * the current time, and not write any field data out, such as
3485     * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>,
3486     * and <code>isSet[]</code>.  <code>nextStamp</code> also should not be part
3487     * of the persistent state. Unfortunately, this didn't happen before JDK 1.1
3488     * shipped. To be compatible with JDK 1.1, we will always have to write out
3489     * the field values and state flags.  However, <code>nextStamp</code> can be
3490     * removed from the serialization stream; this will probably happen in the
3491     * near future.
3492     */
3493    private synchronized void writeObject(ObjectOutputStream stream)
3494         throws IOException
3495    {
3496        // Try to compute the time correctly, for the future (stream
3497        // version 2) in which we don't write out fields[] or isSet[].
3498        if (!isTimeSet) {
3499            try {
3500                updateTime();
3501            }
3502            catch (IllegalArgumentException e) {}
3503        }
3504
3505        // Android-changed: Removed ZoneInfo support/workaround.
3506        // Write out the 1.1 FCS object.
3507        stream.defaultWriteObject();
3508    }
3509
3510    private static class CalendarAccessControlContext {
3511        private static final AccessControlContext INSTANCE;
3512        static {
3513            RuntimePermission perm = new RuntimePermission("accessClassInPackage.sun.util.calendar");
3514            PermissionCollection perms = perm.newPermissionCollection();
3515            perms.add(perm);
3516            INSTANCE = new AccessControlContext(new ProtectionDomain[] {
3517                                                    new ProtectionDomain(null, perms)
3518                                                });
3519        }
3520        private CalendarAccessControlContext() {
3521        }
3522    }
3523
3524    /**
3525     * Reconstitutes this object from a stream (i.e., deserialize it).
3526     */
3527    private void readObject(ObjectInputStream stream)
3528         throws IOException, ClassNotFoundException
3529    {
3530        final ObjectInputStream input = stream;
3531        input.defaultReadObject();
3532
3533        stamp = new int[FIELD_COUNT];
3534
3535        // Starting with version 2 (not implemented yet), we expect that
3536        // fields[], isSet[], isTimeSet, and areFieldsSet may not be
3537        // streamed out anymore.  We expect 'time' to be correct.
3538        if (serialVersionOnStream >= 2)
3539        {
3540            isTimeSet = true;
3541            if (fields == null) {
3542                fields = new int[FIELD_COUNT];
3543            }
3544            if (isSet == null) {
3545                isSet = new boolean[FIELD_COUNT];
3546            }
3547        }
3548        else if (serialVersionOnStream >= 0)
3549        {
3550            for (int i=0; i<FIELD_COUNT; ++i) {
3551                stamp[i] = isSet[i] ? COMPUTED : UNSET;
3552            }
3553        }
3554
3555        serialVersionOnStream = currentSerialVersion;
3556
3557        // Android-changed: removed ZoneInfo support.
3558
3559        // If the deserialized object has a SimpleTimeZone, try to
3560        // replace it with a ZoneInfo equivalent (as of 1.4) in order
3561        // to be compatible with the SimpleTimeZone-based
3562        // implementation as much as possible.
3563        if (zone instanceof SimpleTimeZone) {
3564            String id = zone.getID();
3565            TimeZone tz = TimeZone.getTimeZone(id);
3566            if (tz != null && tz.hasSameRules(zone) && tz.getID().equals(id)) {
3567                zone = tz;
3568            }
3569        }
3570    }
3571
3572    /**
3573     * Converts this object to an {@link Instant}.
3574     * <p>
3575     * The conversion creates an {@code Instant} that represents the
3576     * same point on the time-line as this {@code Calendar}.
3577     *
3578     * @return the instant representing the same point on the time-line
3579     * @since 1.8
3580     */
3581    public final Instant toInstant() {
3582        return Instant.ofEpochMilli(getTimeInMillis());
3583    }
3584}
3585