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