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