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