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