1 /*
   2  * Copyright (c) 1996, 2016, 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, 1997 - All Rights Reserved
  28  * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
  29  *
  30  * The original version of this source code and documentation
  31  * is copyrighted and owned by Taligent, Inc., a wholly-owned
  32  * subsidiary of IBM. These materials are provided under terms
  33  * of a License Agreement between Taligent and Sun. This technology
  34  * is protected by multiple US and International patents.
  35  *
  36  * This notice and attribution to Taligent may not be removed.
  37  * Taligent is a registered trademark of Taligent, Inc.
  38  *
  39  */
  40 
  41 package java.util;
  42 
  43 import java.io.IOException;
  44 import java.io.ObjectInputStream;
  45 import java.io.ObjectOutputStream;
  46 import java.io.ObjectStreamField;
  47 import java.io.Serializable;
  48 import java.text.MessageFormat;
  49 import java.util.concurrent.ConcurrentHashMap;
  50 import java.util.spi.LocaleNameProvider;
  51 
  52 import sun.security.action.GetPropertyAction;
  53 import sun.util.locale.BaseLocale;
  54 import sun.util.locale.InternalLocaleBuilder;
  55 import sun.util.locale.LanguageTag;
  56 import sun.util.locale.LocaleExtensions;
  57 import sun.util.locale.LocaleMatcher;
  58 import sun.util.locale.LocaleObjectCache;
  59 import sun.util.locale.LocaleSyntaxException;
  60 import sun.util.locale.LocaleUtils;
  61 import sun.util.locale.ParseStatus;
  62 import sun.util.locale.provider.LocaleProviderAdapter;
  63 import sun.util.locale.provider.LocaleResources;
  64 import sun.util.locale.provider.LocaleServiceProviderPool;
  65 
  66 /**
  67  * A <code>Locale</code> object represents a specific geographical, political,
  68  * or cultural region. An operation that requires a <code>Locale</code> to perform
  69  * its task is called <em>locale-sensitive</em> and uses the <code>Locale</code>
  70  * to tailor information for the user. For example, displaying a number
  71  * is a locale-sensitive operation&mdash; the number should be formatted
  72  * according to the customs and conventions of the user's native country,
  73  * region, or culture.
  74  *
  75  * <p> The {@code Locale} class implements IETF BCP 47 which is composed of
  76  * <a href="http://tools.ietf.org/html/rfc4647">RFC 4647 "Matching of Language
  77  * Tags"</a> and <a href="http://tools.ietf.org/html/rfc5646">RFC 5646 "Tags
  78  * for Identifying Languages"</a> with support for the LDML (UTS#35, "Unicode
  79  * Locale Data Markup Language") BCP 47-compatible extensions for locale data
  80  * exchange.
  81  *
  82  * <p> A <code>Locale</code> object logically consists of the fields
  83  * described below.
  84  *
  85  * <dl>
  86  *   <dt><a id="def_language"><b>language</b></a></dt>
  87  *
  88  *   <dd>ISO 639 alpha-2 or alpha-3 language code, or registered
  89  *   language subtags up to 8 alpha letters (for future enhancements).
  90  *   When a language has both an alpha-2 code and an alpha-3 code, the
  91  *   alpha-2 code must be used.  You can find a full list of valid
  92  *   language codes in the IANA Language Subtag Registry (search for
  93  *   "Type: language").  The language field is case insensitive, but
  94  *   <code>Locale</code> always canonicalizes to lower case.</dd>
  95  *
  96  *   <dd>Well-formed language values have the form
  97  *   <code>[a-zA-Z]{2,8}</code>.  Note that this is not the full
  98  *   BCP47 language production, since it excludes extlang.  They are
  99  *   not needed since modern three-letter language codes replace
 100  *   them.</dd>
 101  *
 102  *   <dd>Example: "en" (English), "ja" (Japanese), "kok" (Konkani)</dd>
 103  *
 104  *   <dt><a id="def_script"><b>script</b></a></dt>
 105  *
 106  *   <dd>ISO 15924 alpha-4 script code.  You can find a full list of
 107  *   valid script codes in the IANA Language Subtag Registry (search
 108  *   for "Type: script").  The script field is case insensitive, but
 109  *   <code>Locale</code> always canonicalizes to title case (the first
 110  *   letter is upper case and the rest of the letters are lower
 111  *   case).</dd>
 112  *
 113  *   <dd>Well-formed script values have the form
 114  *   <code>[a-zA-Z]{4}</code></dd>
 115  *
 116  *   <dd>Example: "Latn" (Latin), "Cyrl" (Cyrillic)</dd>
 117  *
 118  *   <dt><a id="def_region"><b>country (region)</b></a></dt>
 119  *
 120  *   <dd>ISO 3166 alpha-2 country code or UN M.49 numeric-3 area code.
 121  *   You can find a full list of valid country and region codes in the
 122  *   IANA Language Subtag Registry (search for "Type: region").  The
 123  *   country (region) field is case insensitive, but
 124  *   <code>Locale</code> always canonicalizes to upper case.</dd>
 125  *
 126  *   <dd>Well-formed country/region values have
 127  *   the form <code>[a-zA-Z]{2} | [0-9]{3}</code></dd>
 128  *
 129  *   <dd>Example: "US" (United States), "FR" (France), "029"
 130  *   (Caribbean)</dd>
 131  *
 132  *   <dt><a id="def_variant"><b>variant</b></a></dt>
 133  *
 134  *   <dd>Any arbitrary value used to indicate a variation of a
 135  *   <code>Locale</code>.  Where there are two or more variant values
 136  *   each indicating its own semantics, these values should be ordered
 137  *   by importance, with most important first, separated by
 138  *   underscore('_').  The variant field is case sensitive.</dd>
 139  *
 140  *   <dd>Note: IETF BCP 47 places syntactic restrictions on variant
 141  *   subtags.  Also BCP 47 subtags are strictly used to indicate
 142  *   additional variations that define a language or its dialects that
 143  *   are not covered by any combinations of language, script and
 144  *   region subtags.  You can find a full list of valid variant codes
 145  *   in the IANA Language Subtag Registry (search for "Type: variant").
 146  *
 147  *   <p>However, the variant field in <code>Locale</code> has
 148  *   historically been used for any kind of variation, not just
 149  *   language variations.  For example, some supported variants
 150  *   available in Java SE Runtime Environments indicate alternative
 151  *   cultural behaviors such as calendar type or number script.  In
 152  *   BCP 47 this kind of information, which does not identify the
 153  *   language, is supported by extension subtags or private use
 154  *   subtags.</dd>
 155  *
 156  *   <dd>Well-formed variant values have the form <code>SUBTAG
 157  *   (('_'|'-') SUBTAG)*</code> where <code>SUBTAG =
 158  *   [0-9][0-9a-zA-Z]{3} | [0-9a-zA-Z]{5,8}</code>. (Note: BCP 47 only
 159  *   uses hyphen ('-') as a delimiter, this is more lenient).</dd>
 160  *
 161  *   <dd>Example: "polyton" (Polytonic Greek), "POSIX"</dd>
 162  *
 163  *   <dt><a id="def_extensions"><b>extensions</b></a></dt>
 164  *
 165  *   <dd>A map from single character keys to string values, indicating
 166  *   extensions apart from language identification.  The extensions in
 167  *   <code>Locale</code> implement the semantics and syntax of BCP 47
 168  *   extension subtags and private use subtags. The extensions are
 169  *   case insensitive, but <code>Locale</code> canonicalizes all
 170  *   extension keys and values to lower case. Note that extensions
 171  *   cannot have empty values.</dd>
 172  *
 173  *   <dd>Well-formed keys are single characters from the set
 174  *   <code>[0-9a-zA-Z]</code>.  Well-formed values have the form
 175  *   <code>SUBTAG ('-' SUBTAG)*</code> where for the key 'x'
 176  *   <code>SUBTAG = [0-9a-zA-Z]{1,8}</code> and for other keys
 177  *   <code>SUBTAG = [0-9a-zA-Z]{2,8}</code> (that is, 'x' allows
 178  *   single-character subtags).</dd>
 179  *
 180  *   <dd>Example: key="u"/value="ca-japanese" (Japanese Calendar),
 181  *   key="x"/value="java-1-7"</dd>
 182  * </dl>
 183  *
 184  * <b>Note:</b> Although BCP 47 requires field values to be registered
 185  * in the IANA Language Subtag Registry, the <code>Locale</code> class
 186  * does not provide any validation features.  The <code>Builder</code>
 187  * only checks if an individual field satisfies the syntactic
 188  * requirement (is well-formed), but does not validate the value
 189  * itself.  See {@link Builder} for details.
 190  *
 191  * <h3><a id="def_locale_extension">Unicode locale/language extension</a></h3>
 192  *
 193  * <p>UTS#35, "Unicode Locale Data Markup Language" defines optional
 194  * attributes and keywords to override or refine the default behavior
 195  * associated with a locale.  A keyword is represented by a pair of
 196  * key and type.  For example, "nu-thai" indicates that Thai local
 197  * digits (value:"thai") should be used for formatting numbers
 198  * (key:"nu").
 199  *
 200  * <p>The keywords are mapped to a BCP 47 extension value using the
 201  * extension key 'u' ({@link #UNICODE_LOCALE_EXTENSION}).  The above
 202  * example, "nu-thai", becomes the extension "u-nu-thai".
 203  *
 204  * <p>Thus, when a <code>Locale</code> object contains Unicode locale
 205  * attributes and keywords,
 206  * <code>getExtension(UNICODE_LOCALE_EXTENSION)</code> will return a
 207  * String representing this information, for example, "nu-thai".  The
 208  * <code>Locale</code> class also provides {@link
 209  * #getUnicodeLocaleAttributes}, {@link #getUnicodeLocaleKeys}, and
 210  * {@link #getUnicodeLocaleType} which allow you to access Unicode
 211  * locale attributes and key/type pairs directly.  When represented as
 212  * a string, the Unicode Locale Extension lists attributes
 213  * alphabetically, followed by key/type sequences with keys listed
 214  * alphabetically (the order of subtags comprising a key's type is
 215  * fixed when the type is defined)
 216  *
 217  * <p>A well-formed locale key has the form
 218  * <code>[0-9a-zA-Z]{2}</code>.  A well-formed locale type has the
 219  * form <code>"" | [0-9a-zA-Z]{3,8} ('-' [0-9a-zA-Z]{3,8})*</code> (it
 220  * can be empty, or a series of subtags 3-8 alphanums in length).  A
 221  * well-formed locale attribute has the form
 222  * <code>[0-9a-zA-Z]{3,8}</code> (it is a single subtag with the same
 223  * form as a locale type subtag).
 224  *
 225  * <p>The Unicode locale extension specifies optional behavior in
 226  * locale-sensitive services.  Although the LDML specification defines
 227  * various keys and values, actual locale-sensitive service
 228  * implementations in a Java Runtime Environment might not support any
 229  * particular Unicode locale attributes or key/type pairs.
 230  *
 231  * <h4>Creating a Locale</h4>
 232  *
 233  * <p>There are several different ways to create a <code>Locale</code>
 234  * object.
 235  *
 236  * <h5>Builder</h5>
 237  *
 238  * <p>Using {@link Builder} you can construct a <code>Locale</code> object
 239  * that conforms to BCP 47 syntax.
 240  *
 241  * <h5>Constructors</h5>
 242  *
 243  * <p>The <code>Locale</code> class provides three constructors:
 244  * <blockquote>
 245  * <pre>
 246  *     {@link #Locale(String language)}
 247  *     {@link #Locale(String language, String country)}
 248  *     {@link #Locale(String language, String country, String variant)}
 249  * </pre>
 250  * </blockquote>
 251  * These constructors allow you to create a <code>Locale</code> object
 252  * with language, country and variant, but you cannot specify
 253  * script or extensions.
 254  *
 255  * <h5>Factory Methods</h5>
 256  *
 257  * <p>The method {@link #forLanguageTag} creates a <code>Locale</code>
 258  * object for a well-formed BCP 47 language tag.
 259  *
 260  * <h5>Locale Constants</h5>
 261  *
 262  * <p>The <code>Locale</code> class provides a number of convenient constants
 263  * that you can use to create <code>Locale</code> objects for commonly used
 264  * locales. For example, the following creates a <code>Locale</code> object
 265  * for the United States:
 266  * <blockquote>
 267  * <pre>
 268  *     Locale.US
 269  * </pre>
 270  * </blockquote>
 271  *
 272  * <h4><a id="LocaleMatching">Locale Matching</a></h4>
 273  *
 274  * <p>If an application or a system is internationalized and provides localized
 275  * resources for multiple locales, it sometimes needs to find one or more
 276  * locales (or language tags) which meet each user's specific preferences. Note
 277  * that a term "language tag" is used interchangeably with "locale" in this
 278  * locale matching documentation.
 279  *
 280  * <p>In order to do matching a user's preferred locales to a set of language
 281  * tags, <a href="http://tools.ietf.org/html/rfc4647">RFC 4647 Matching of
 282  * Language Tags</a> defines two mechanisms: filtering and lookup.
 283  * <em>Filtering</em> is used to get all matching locales, whereas
 284  * <em>lookup</em> is to choose the best matching locale.
 285  * Matching is done case-insensitively. These matching mechanisms are described
 286  * in the following sections.
 287  *
 288  * <p>A user's preference is called a <em>Language Priority List</em> and is
 289  * expressed as a list of language ranges. There are syntactically two types of
 290  * language ranges: basic and extended. See
 291  * {@link Locale.LanguageRange Locale.LanguageRange} for details.
 292  *
 293  * <h5>Filtering</h5>
 294  *
 295  * <p>The filtering operation returns all matching language tags. It is defined
 296  * in RFC 4647 as follows:
 297  * "In filtering, each language range represents the least specific language
 298  * tag (that is, the language tag with fewest number of subtags) that is an
 299  * acceptable match. All of the language tags in the matching set of tags will
 300  * have an equal or greater number of subtags than the language range. Every
 301  * non-wildcard subtag in the language range will appear in every one of the
 302  * matching language tags."
 303  *
 304  * <p>There are two types of filtering: filtering for basic language ranges
 305  * (called "basic filtering") and filtering for extended language ranges
 306  * (called "extended filtering"). They may return different results by what
 307  * kind of language ranges are included in the given Language Priority List.
 308  * {@link Locale.FilteringMode} is a parameter to specify how filtering should
 309  * be done.
 310  *
 311  * <h5>Lookup</h5>
 312  *
 313  * <p>The lookup operation returns the best matching language tags. It is
 314  * defined in RFC 4647 as follows:
 315  * "By contrast with filtering, each language range represents the most
 316  * specific tag that is an acceptable match.  The first matching tag found,
 317  * according to the user's priority, is considered the closest match and is the
 318  * item returned."
 319  *
 320  * <p>For example, if a Language Priority List consists of two language ranges,
 321  * {@code "zh-Hant-TW"} and {@code "en-US"}, in prioritized order, lookup
 322  * method progressively searches the language tags below in order to find the
 323  * best matching language tag.
 324  * <blockquote>
 325  * <pre>
 326  *    1. zh-Hant-TW
 327  *    2. zh-Hant
 328  *    3. zh
 329  *    4. en-US
 330  *    5. en
 331  * </pre>
 332  * </blockquote>
 333  * If there is a language tag which matches completely to a language range
 334  * above, the language tag is returned.
 335  *
 336  * <p>{@code "*"} is the special language range, and it is ignored in lookup.
 337  *
 338  * <p>If multiple language tags match as a result of the subtag {@code '*'}
 339  * included in a language range, the first matching language tag returned by
 340  * an {@link Iterator} over a {@link Collection} of language tags is treated as
 341  * the best matching one.
 342  *
 343  * <h4>Use of Locale</h4>
 344  *
 345  * <p>Once you've created a <code>Locale</code> you can query it for information
 346  * about itself. Use <code>getCountry</code> to get the country (or region)
 347  * code and <code>getLanguage</code> to get the language code.
 348  * You can use <code>getDisplayCountry</code> to get the
 349  * name of the country suitable for displaying to the user. Similarly,
 350  * you can use <code>getDisplayLanguage</code> to get the name of
 351  * the language suitable for displaying to the user. Interestingly,
 352  * the <code>getDisplayXXX</code> methods are themselves locale-sensitive
 353  * and have two versions: one that uses the default
 354  * {@link Locale.Category#DISPLAY DISPLAY} locale and one
 355  * that uses the locale specified as an argument.
 356  *
 357  * <p>The Java Platform provides a number of classes that perform locale-sensitive
 358  * operations. For example, the <code>NumberFormat</code> class formats
 359  * numbers, currency, and percentages in a locale-sensitive manner. Classes
 360  * such as <code>NumberFormat</code> have several convenience methods
 361  * for creating a default object of that type. For example, the
 362  * <code>NumberFormat</code> class provides these three convenience methods
 363  * for creating a default <code>NumberFormat</code> object:
 364  * <blockquote>
 365  * <pre>
 366  *     NumberFormat.getInstance()
 367  *     NumberFormat.getCurrencyInstance()
 368  *     NumberFormat.getPercentInstance()
 369  * </pre>
 370  * </blockquote>
 371  * Each of these methods has two variants; one with an explicit locale
 372  * and one without; the latter uses the default
 373  * {@link Locale.Category#FORMAT FORMAT} locale:
 374  * <blockquote>
 375  * <pre>
 376  *     NumberFormat.getInstance(myLocale)
 377  *     NumberFormat.getCurrencyInstance(myLocale)
 378  *     NumberFormat.getPercentInstance(myLocale)
 379  * </pre>
 380  * </blockquote>
 381  * A <code>Locale</code> is the mechanism for identifying the kind of object
 382  * (<code>NumberFormat</code>) that you would like to get. The locale is
 383  * <STRONG>just</STRONG> a mechanism for identifying objects,
 384  * <STRONG>not</STRONG> a container for the objects themselves.
 385  *
 386  * <h4>Compatibility</h4>
 387  *
 388  * <p>In order to maintain compatibility with existing usage, Locale's
 389  * constructors retain their behavior prior to the Java Runtime
 390  * Environment version 1.7.  The same is largely true for the
 391  * <code>toString</code> method. Thus Locale objects can continue to
 392  * be used as they were. In particular, clients who parse the output
 393  * of toString into language, country, and variant fields can continue
 394  * to do so (although this is strongly discouraged), although the
 395  * variant field will have additional information in it if script or
 396  * extensions are present.
 397  *
 398  * <p>In addition, BCP 47 imposes syntax restrictions that are not
 399  * imposed by Locale's constructors. This means that conversions
 400  * between some Locales and BCP 47 language tags cannot be made without
 401  * losing information. Thus <code>toLanguageTag</code> cannot
 402  * represent the state of locales whose language, country, or variant
 403  * do not conform to BCP 47.
 404  *
 405  * <p>Because of these issues, it is recommended that clients migrate
 406  * away from constructing non-conforming locales and use the
 407  * <code>forLanguageTag</code> and <code>Locale.Builder</code> APIs instead.
 408  * Clients desiring a string representation of the complete locale can
 409  * then always rely on <code>toLanguageTag</code> for this purpose.
 410  *
 411  * <h5><a id="special_cases_constructor">Special cases</a></h5>
 412  *
 413  * <p>For compatibility reasons, two
 414  * non-conforming locales are treated as special cases.  These are
 415  * <b>{@code ja_JP_JP}</b> and <b>{@code th_TH_TH}</b>. These are ill-formed
 416  * in BCP 47 since the variants are too short. To ease migration to BCP 47,
 417  * these are treated specially during construction.  These two cases (and only
 418  * these) cause a constructor to generate an extension, all other values behave
 419  * exactly as they did prior to Java 7.
 420  *
 421  * <p>Java has used {@code ja_JP_JP} to represent Japanese as used in
 422  * Japan together with the Japanese Imperial calendar. This is now
 423  * representable using a Unicode locale extension, by specifying the
 424  * Unicode locale key {@code ca} (for "calendar") and type
 425  * {@code japanese}. When the Locale constructor is called with the
 426  * arguments "ja", "JP", "JP", the extension "u-ca-japanese" is
 427  * automatically added.
 428  *
 429  * <p>Java has used {@code th_TH_TH} to represent Thai as used in
 430  * Thailand together with Thai digits. This is also now representable using
 431  * a Unicode locale extension, by specifying the Unicode locale key
 432  * {@code nu} (for "number") and value {@code thai}. When the Locale
 433  * constructor is called with the arguments "th", "TH", "TH", the
 434  * extension "u-nu-thai" is automatically added.
 435  *
 436  * <h5>Serialization</h5>
 437  *
 438  * <p>During serialization, writeObject writes all fields to the output
 439  * stream, including extensions.
 440  *
 441  * <p>During deserialization, readResolve adds extensions as described
 442  * in <a href="#special_cases_constructor">Special Cases</a>, only
 443  * for the two cases th_TH_TH and ja_JP_JP.
 444  *
 445  * <h5>Legacy language codes</h5>
 446  *
 447  * <p>Locale's constructor has always converted three language codes to
 448  * their earlier, obsoleted forms: {@code he} maps to {@code iw},
 449  * {@code yi} maps to {@code ji}, and {@code id} maps to
 450  * {@code in}.  This continues to be the case, in order to not break
 451  * backwards compatibility.
 452  *
 453  * <p>The APIs added in 1.7 map between the old and new language codes,
 454  * maintaining the old codes internal to Locale (so that
 455  * <code>getLanguage</code> and <code>toString</code> reflect the old
 456  * code), but using the new codes in the BCP 47 language tag APIs (so
 457  * that <code>toLanguageTag</code> reflects the new one). This
 458  * preserves the equivalence between Locales no matter which code or
 459  * API is used to construct them. Java's default resource bundle
 460  * lookup mechanism also implements this mapping, so that resources
 461  * can be named using either convention, see {@link ResourceBundle.Control}.
 462  *
 463  * <h5>Three-letter language/country(region) codes</h5>
 464  *
 465  * <p>The Locale constructors have always specified that the language
 466  * and the country param be two characters in length, although in
 467  * practice they have accepted any length.  The specification has now
 468  * been relaxed to allow language codes of two to eight characters and
 469  * country (region) codes of two to three characters, and in
 470  * particular, three-letter language codes and three-digit region
 471  * codes as specified in the IANA Language Subtag Registry.  For
 472  * compatibility, the implementation still does not impose a length
 473  * constraint.
 474  *
 475  * @see Builder
 476  * @see ResourceBundle
 477  * @see java.text.Format
 478  * @see java.text.NumberFormat
 479  * @see java.text.Collator
 480  * @author Mark Davis
 481  * @since 1.1
 482  */
 483 public final class Locale implements Cloneable, Serializable {
 484 
 485     private static final  Cache LOCALECACHE = new Cache();
 486 
 487     /** Useful constant for language.
 488      */
 489     public static final Locale ENGLISH = createConstant("en", "");
 490 
 491     /** Useful constant for language.
 492      */
 493     public static final Locale FRENCH = createConstant("fr", "");
 494 
 495     /** Useful constant for language.
 496      */
 497     public static final Locale GERMAN = createConstant("de", "");
 498 
 499     /** Useful constant for language.
 500      */
 501     public static final Locale ITALIAN = createConstant("it", "");
 502 
 503     /** Useful constant for language.
 504      */
 505     public static final Locale JAPANESE = createConstant("ja", "");
 506 
 507     /** Useful constant for language.
 508      */
 509     public static final Locale KOREAN = createConstant("ko", "");
 510 
 511     /** Useful constant for language.
 512      */
 513     public static final Locale CHINESE = createConstant("zh", "");
 514 
 515     /** Useful constant for language.
 516      */
 517     public static final Locale SIMPLIFIED_CHINESE = createConstant("zh", "CN");
 518 
 519     /** Useful constant for language.
 520      */
 521     public static final Locale TRADITIONAL_CHINESE = createConstant("zh", "TW");
 522 
 523     /** Useful constant for country.
 524      */
 525     public static final Locale FRANCE = createConstant("fr", "FR");
 526 
 527     /** Useful constant for country.
 528      */
 529     public static final Locale GERMANY = createConstant("de", "DE");
 530 
 531     /** Useful constant for country.
 532      */
 533     public static final Locale ITALY = createConstant("it", "IT");
 534 
 535     /** Useful constant for country.
 536      */
 537     public static final Locale JAPAN = createConstant("ja", "JP");
 538 
 539     /** Useful constant for country.
 540      */
 541     public static final Locale KOREA = createConstant("ko", "KR");
 542 
 543     /** Useful constant for country.
 544      */
 545     public static final Locale CHINA = SIMPLIFIED_CHINESE;
 546 
 547     /** Useful constant for country.
 548      */
 549     public static final Locale PRC = SIMPLIFIED_CHINESE;
 550 
 551     /** Useful constant for country.
 552      */
 553     public static final Locale TAIWAN = TRADITIONAL_CHINESE;
 554 
 555     /** Useful constant for country.
 556      */
 557     public static final Locale UK = createConstant("en", "GB");
 558 
 559     /** Useful constant for country.
 560      */
 561     public static final Locale US = createConstant("en", "US");
 562 
 563     /** Useful constant for country.
 564      */
 565     public static final Locale CANADA = createConstant("en", "CA");
 566 
 567     /** Useful constant for country.
 568      */
 569     public static final Locale CANADA_FRENCH = createConstant("fr", "CA");
 570 
 571     /**
 572      * Useful constant for the root locale.  The root locale is the locale whose
 573      * language, country, and variant are empty ("") strings.  This is regarded
 574      * as the base locale of all locales, and is used as the language/country
 575      * neutral locale for the locale sensitive operations.
 576      *
 577      * @since 1.6
 578      */
 579     public static final Locale ROOT = createConstant("", "");
 580 
 581     /**
 582      * The key for the private use extension ('x').
 583      *
 584      * @see #getExtension(char)
 585      * @see Builder#setExtension(char, String)
 586      * @since 1.7
 587      */
 588     public static final char PRIVATE_USE_EXTENSION = 'x';
 589 
 590     /**
 591      * The key for Unicode locale extension ('u').
 592      *
 593      * @see #getExtension(char)
 594      * @see Builder#setExtension(char, String)
 595      * @since 1.7
 596      */
 597     public static final char UNICODE_LOCALE_EXTENSION = 'u';
 598 
 599     /** serialization ID
 600      */
 601     static final long serialVersionUID = 9149081749638150636L;
 602 
 603     /**
 604      * Enum for specifying the type defined in ISO 3166. This enum is used to
 605      * retrieve the two-letter ISO3166-1 alpha-2, three-letter ISO3166-1
 606      * alpha-3, four-letter ISO3166-3 country codes.
 607      *
 608      * @see #getISOCountries(Locale.IsoCountryCode)
 609      * @since 9
 610      */
 611     public static enum IsoCountryCode {
 612         /**
 613          * PART1_ALPHA2 is used to represent the ISO3166-1 alpha-2 two letter
 614          * country codes.
 615          */
 616         PART1_ALPHA2 {
 617             @Override
 618             Set<String> createCountryCodeSet() {
 619                 return Set.of(Locale.getISOCountries());
 620             }
 621         },
 622 
 623         /**
 624          *
 625          * PART1_ALPHA3 is used to represent the ISO3166-1 alpha-3 three letter
 626          * country codes.
 627          */
 628         PART1_ALPHA3 {
 629             @Override
 630             Set<String> createCountryCodeSet() {
 631                 return LocaleISOData.computeISO3166_1Alpha3Countries();
 632             }
 633         },
 634 
 635         /**
 636          * PART3 is used to represent the ISO3166-3 four letter country codes.
 637          */
 638         PART3 {
 639             @Override
 640             Set<String> createCountryCodeSet() {
 641                 return Set.of(LocaleISOData.ISO3166_3);
 642             }
 643         };
 644 
 645         /**
 646          * Concrete implementation of this method attempts to compute value
 647          * for iso3166CodesMap for each IsoCountryCode type key.
 648          */
 649         abstract Set<String> createCountryCodeSet();
 650 
 651         /**
 652          * Map to hold country codes for each ISO3166 part.
 653          */
 654         private static Map<IsoCountryCode, Set<String>> iso3166CodesMap = new ConcurrentHashMap<>();
 655 
 656         /**
 657          * This method is called from Locale class to retrieve country code set
 658          * for getISOCountries(type)
 659          */
 660         static Set<String> retrieveISOCountryCodes(IsoCountryCode type) {
 661             return iso3166CodesMap.computeIfAbsent(type, IsoCountryCode::createCountryCodeSet);
 662         }
 663     }
 664 
 665     /**
 666      * Display types for retrieving localized names from the name providers.
 667      */
 668     private static final int DISPLAY_LANGUAGE = 0;
 669     private static final int DISPLAY_COUNTRY  = 1;
 670     private static final int DISPLAY_VARIANT  = 2;
 671     private static final int DISPLAY_SCRIPT   = 3;
 672 
 673     /**
 674      * Private constructor used by getInstance method
 675      */
 676     private Locale(BaseLocale baseLocale, LocaleExtensions extensions) {
 677         this.baseLocale = baseLocale;
 678         this.localeExtensions = extensions;
 679     }
 680 
 681     /**
 682      * Construct a locale from language, country and variant.
 683      * This constructor normalizes the language value to lowercase and
 684      * the country value to uppercase.
 685      * <p>
 686      * <b>Note:</b>
 687      * <ul>
 688      * <li>ISO 639 is not a stable standard; some of the language codes it defines
 689      * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
 690      * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
 691      * API on Locale will return only the OLD codes.
 692      * <li>For backward compatibility reasons, this constructor does not make
 693      * any syntactic checks on the input.
 694      * <li>The two cases ("ja", "JP", "JP") and ("th", "TH", "TH") are handled specially,
 695      * see <a href="#special_cases_constructor">Special Cases</a> for more information.
 696      * </ul>
 697      *
 698      * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
 699      * up to 8 characters in length.  See the <code>Locale</code> class description about
 700      * valid language values.
 701      * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code.
 702      * See the <code>Locale</code> class description about valid country values.
 703      * @param variant Any arbitrary value used to indicate a variation of a <code>Locale</code>.
 704      * See the <code>Locale</code> class description for the details.
 705      * @exception NullPointerException thrown if any argument is null.
 706      */
 707     public Locale(String language, String country, String variant) {
 708         if (language== null || country == null || variant == null) {
 709             throw new NullPointerException();
 710         }
 711         baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), "", country, variant);
 712         localeExtensions = getCompatibilityExtensions(language, "", country, variant);
 713     }
 714 
 715     /**
 716      * Construct a locale from language and country.
 717      * This constructor normalizes the language value to lowercase and
 718      * the country value to uppercase.
 719      * <p>
 720      * <b>Note:</b>
 721      * <ul>
 722      * <li>ISO 639 is not a stable standard; some of the language codes it defines
 723      * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
 724      * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
 725      * API on Locale will return only the OLD codes.
 726      * <li>For backward compatibility reasons, this constructor does not make
 727      * any syntactic checks on the input.
 728      * </ul>
 729      *
 730      * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
 731      * up to 8 characters in length.  See the <code>Locale</code> class description about
 732      * valid language values.
 733      * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code.
 734      * See the <code>Locale</code> class description about valid country values.
 735      * @exception NullPointerException thrown if either argument is null.
 736      */
 737     public Locale(String language, String country) {
 738         this(language, country, "");
 739     }
 740 
 741     /**
 742      * Construct a locale from a language code.
 743      * This constructor normalizes the language value to lowercase.
 744      * <p>
 745      * <b>Note:</b>
 746      * <ul>
 747      * <li>ISO 639 is not a stable standard; some of the language codes it defines
 748      * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
 749      * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
 750      * API on Locale will return only the OLD codes.
 751      * <li>For backward compatibility reasons, this constructor does not make
 752      * any syntactic checks on the input.
 753      * </ul>
 754      *
 755      * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
 756      * up to 8 characters in length.  See the <code>Locale</code> class description about
 757      * valid language values.
 758      * @exception NullPointerException thrown if argument is null.
 759      * @since 1.4
 760      */
 761     public Locale(String language) {
 762         this(language, "", "");
 763     }
 764 
 765     /**
 766      * This method must be called only for creating the Locale.*
 767      * constants due to making shortcuts.
 768      */
 769     private static Locale createConstant(String lang, String country) {
 770         BaseLocale base = BaseLocale.createInstance(lang, country);
 771         return getInstance(base, null);
 772     }
 773 
 774     /**
 775      * Returns a <code>Locale</code> constructed from the given
 776      * <code>language</code>, <code>country</code> and
 777      * <code>variant</code>. If the same <code>Locale</code> instance
 778      * is available in the cache, then that instance is
 779      * returned. Otherwise, a new <code>Locale</code> instance is
 780      * created and cached.
 781      *
 782      * @param language lowercase 2 to 8 language code.
 783      * @param country uppercase two-letter ISO-3166 code and numeric-3 UN M.49 area code.
 784      * @param variant vendor and browser specific code. See class description.
 785      * @return the <code>Locale</code> instance requested
 786      * @exception NullPointerException if any argument is null.
 787      */
 788     static Locale getInstance(String language, String country, String variant) {
 789         return getInstance(language, "", country, variant, null);
 790     }
 791 
 792     static Locale getInstance(String language, String script, String country,
 793                                       String variant, LocaleExtensions extensions) {
 794         if (language== null || script == null || country == null || variant == null) {
 795             throw new NullPointerException();
 796         }
 797 
 798         if (extensions == null) {
 799             extensions = getCompatibilityExtensions(language, script, country, variant);
 800         }
 801 
 802         BaseLocale baseloc = BaseLocale.getInstance(language, script, country, variant);
 803         return getInstance(baseloc, extensions);
 804     }
 805 
 806     static Locale getInstance(BaseLocale baseloc, LocaleExtensions extensions) {
 807         LocaleKey key = new LocaleKey(baseloc, extensions);
 808         return LOCALECACHE.get(key);
 809     }
 810 
 811     private static class Cache extends LocaleObjectCache<LocaleKey, Locale> {
 812         private Cache() {
 813         }
 814 
 815         @Override
 816         protected Locale createObject(LocaleKey key) {
 817             return new Locale(key.base, key.exts);
 818         }
 819     }
 820 
 821     private static final class LocaleKey {
 822         private final BaseLocale base;
 823         private final LocaleExtensions exts;
 824         private final int hash;
 825 
 826         private LocaleKey(BaseLocale baseLocale, LocaleExtensions extensions) {
 827             base = baseLocale;
 828             exts = extensions;
 829 
 830             // Calculate the hash value here because it's always used.
 831             int h = base.hashCode();
 832             if (exts != null) {
 833                 h ^= exts.hashCode();
 834             }
 835             hash = h;
 836         }
 837 
 838         @Override
 839         public boolean equals(Object obj) {
 840             if (this == obj) {
 841                 return true;
 842             }
 843             if (!(obj instanceof LocaleKey)) {
 844                 return false;
 845             }
 846             LocaleKey other = (LocaleKey)obj;
 847             if (hash != other.hash || !base.equals(other.base)) {
 848                 return false;
 849             }
 850             if (exts == null) {
 851                 return other.exts == null;
 852             }
 853             return exts.equals(other.exts);
 854         }
 855 
 856         @Override
 857         public int hashCode() {
 858             return hash;
 859         }
 860     }
 861 
 862     /**
 863      * Gets the current value of the default locale for this instance
 864      * of the Java Virtual Machine.
 865      * <p>
 866      * The Java Virtual Machine sets the default locale during startup
 867      * based on the host environment. It is used by many locale-sensitive
 868      * methods if no locale is explicitly specified.
 869      * It can be changed using the
 870      * {@link #setDefault(java.util.Locale) setDefault} method.
 871      *
 872      * @return the default locale for this instance of the Java Virtual Machine
 873      */
 874     public static Locale getDefault() {
 875         // do not synchronize this method - see 4071298
 876         return defaultLocale;
 877     }
 878 
 879     /**
 880      * Gets the current value of the default locale for the specified Category
 881      * for this instance of the Java Virtual Machine.
 882      * <p>
 883      * The Java Virtual Machine sets the default locale during startup based
 884      * on the host environment. It is used by many locale-sensitive methods
 885      * if no locale is explicitly specified. It can be changed using the
 886      * setDefault(Locale.Category, Locale) method.
 887      *
 888      * @param category - the specified category to get the default locale
 889      * @throws NullPointerException if category is null
 890      * @return the default locale for the specified Category for this instance
 891      *     of the Java Virtual Machine
 892      * @see #setDefault(Locale.Category, Locale)
 893      * @since 1.7
 894      */
 895     public static Locale getDefault(Locale.Category category) {
 896         // do not synchronize this method - see 4071298
 897         switch (category) {
 898         case DISPLAY:
 899             if (defaultDisplayLocale == null) {
 900                 synchronized(Locale.class) {
 901                     if (defaultDisplayLocale == null) {
 902                         defaultDisplayLocale = initDefault(category);
 903                     }
 904                 }
 905             }
 906             return defaultDisplayLocale;
 907         case FORMAT:
 908             if (defaultFormatLocale == null) {
 909                 synchronized(Locale.class) {
 910                     if (defaultFormatLocale == null) {
 911                         defaultFormatLocale = initDefault(category);
 912                     }
 913                 }
 914             }
 915             return defaultFormatLocale;
 916         default:
 917             assert false: "Unknown Category";
 918         }
 919         return getDefault();
 920     }
 921 
 922     private static Locale initDefault() {
 923         String language, region, script, country, variant;
 924         Properties props = GetPropertyAction.privilegedGetProperties();
 925         language = props.getProperty("user.language", "en");
 926         // for compatibility, check for old user.region property
 927         region = props.getProperty("user.region");
 928         if (region != null) {
 929             // region can be of form country, country_variant, or _variant
 930             int i = region.indexOf('_');
 931             if (i >= 0) {
 932                 country = region.substring(0, i);
 933                 variant = region.substring(i + 1);
 934             } else {
 935                 country = region;
 936                 variant = "";
 937             }
 938             script = "";
 939         } else {
 940             script = props.getProperty("user.script", "");
 941             country = props.getProperty("user.country", "");
 942             variant = props.getProperty("user.variant", "");
 943         }
 944 
 945         return getInstance(language, script, country, variant, null);
 946     }
 947 
 948     private static Locale initDefault(Locale.Category category) {
 949         Properties props = GetPropertyAction.privilegedGetProperties();
 950         return getInstance(
 951             props.getProperty(category.languageKey,
 952                     defaultLocale.getLanguage()),
 953             props.getProperty(category.scriptKey,
 954                     defaultLocale.getScript()),
 955             props.getProperty(category.countryKey,
 956                     defaultLocale.getCountry()),
 957             props.getProperty(category.variantKey,
 958                     defaultLocale.getVariant()),
 959             null);
 960     }
 961 
 962     /**
 963      * Sets the default locale for this instance of the Java Virtual Machine.
 964      * This does not affect the host locale.
 965      * <p>
 966      * If there is a security manager, its <code>checkPermission</code>
 967      * method is called with a <code>PropertyPermission("user.language", "write")</code>
 968      * permission before the default locale is changed.
 969      * <p>
 970      * The Java Virtual Machine sets the default locale during startup
 971      * based on the host environment. It is used by many locale-sensitive
 972      * methods if no locale is explicitly specified.
 973      * <p>
 974      * Since changing the default locale may affect many different areas
 975      * of functionality, this method should only be used if the caller
 976      * is prepared to reinitialize locale-sensitive code running
 977      * within the same Java Virtual Machine.
 978      * <p>
 979      * By setting the default locale with this method, all of the default
 980      * locales for each Category are also set to the specified default locale.
 981      *
 982      * @throws SecurityException
 983      *        if a security manager exists and its
 984      *        <code>checkPermission</code> method doesn't allow the operation.
 985      * @throws NullPointerException if <code>newLocale</code> is null
 986      * @param newLocale the new default locale
 987      * @see SecurityManager#checkPermission
 988      * @see java.util.PropertyPermission
 989      */
 990     public static synchronized void setDefault(Locale newLocale) {
 991         setDefault(Category.DISPLAY, newLocale);
 992         setDefault(Category.FORMAT, newLocale);
 993         defaultLocale = newLocale;
 994     }
 995 
 996     /**
 997      * Sets the default locale for the specified Category for this instance
 998      * of the Java Virtual Machine. This does not affect the host locale.
 999      * <p>
1000      * If there is a security manager, its checkPermission method is called
1001      * with a PropertyPermission("user.language", "write") permission before
1002      * the default locale is changed.
1003      * <p>
1004      * The Java Virtual Machine sets the default locale during startup based
1005      * on the host environment. It is used by many locale-sensitive methods
1006      * if no locale is explicitly specified.
1007      * <p>
1008      * Since changing the default locale may affect many different areas of
1009      * functionality, this method should only be used if the caller is
1010      * prepared to reinitialize locale-sensitive code running within the
1011      * same Java Virtual Machine.
1012      *
1013      * @param category - the specified category to set the default locale
1014      * @param newLocale - the new default locale
1015      * @throws SecurityException if a security manager exists and its
1016      *     checkPermission method doesn't allow the operation.
1017      * @throws NullPointerException if category and/or newLocale is null
1018      * @see SecurityManager#checkPermission(java.security.Permission)
1019      * @see PropertyPermission
1020      * @see #getDefault(Locale.Category)
1021      * @since 1.7
1022      */
1023     public static synchronized void setDefault(Locale.Category category,
1024         Locale newLocale) {
1025         if (category == null)
1026             throw new NullPointerException("Category cannot be NULL");
1027         if (newLocale == null)
1028             throw new NullPointerException("Can't set default locale to NULL");
1029 
1030         SecurityManager sm = System.getSecurityManager();
1031         if (sm != null) sm.checkPermission(new PropertyPermission
1032                         ("user.language", "write"));
1033         switch (category) {
1034         case DISPLAY:
1035             defaultDisplayLocale = newLocale;
1036             break;
1037         case FORMAT:
1038             defaultFormatLocale = newLocale;
1039             break;
1040         default:
1041             assert false: "Unknown Category";
1042         }
1043     }
1044 
1045     /**
1046      * Returns an array of all installed locales.
1047      * The returned array represents the union of locales supported
1048      * by the Java runtime environment and by installed
1049      * {@link java.util.spi.LocaleServiceProvider LocaleServiceProvider}
1050      * implementations.  It must contain at least a <code>Locale</code>
1051      * instance equal to {@link java.util.Locale#US Locale.US}.
1052      *
1053      * @return An array of installed locales.
1054      */
1055     public static Locale[] getAvailableLocales() {
1056         return LocaleServiceProviderPool.getAllAvailableLocales();
1057     }
1058 
1059     /**
1060      * Returns a list of all 2-letter country codes defined in ISO 3166.
1061      * Can be used to create Locales.
1062      * This method is equivalent to {@link #getISOCountries(Locale.IsoCountryCode type)}
1063      * with {@code type}  {@link IsoCountryCode#PART1_ALPHA2}.
1064      * <p>
1065      * <b>Note:</b> The <code>Locale</code> class also supports other codes for
1066      * country (region), such as 3-letter numeric UN M.49 area codes.
1067      * Therefore, the list returned by this method does not contain ALL valid
1068      * codes that can be used to create Locales.
1069      * <p>
1070      * Note that this method does not return obsolete 2-letter country codes.
1071      * ISO3166-3 codes which designate country codes for those obsolete codes,
1072      * can be retrieved from {@link #getISOCountries(Locale.IsoCountryCode type)} with
1073      * {@code type}  {@link IsoCountryCode#PART3}.
1074      * @return An array of ISO 3166 two-letter country codes.
1075      */
1076     public static String[] getISOCountries() {
1077         if (isoCountries == null) {
1078             isoCountries = getISO2Table(LocaleISOData.isoCountryTable);
1079         }
1080         String[] result = new String[isoCountries.length];
1081         System.arraycopy(isoCountries, 0, result, 0, isoCountries.length);
1082         return result;
1083     }
1084 
1085     /**
1086      * Returns a {@code Set} of ISO3166 country codes for the specified type.
1087      *
1088      * @param type {@link Locale.IsoCountryCode} specified ISO code type.
1089      * @see java.util.Locale.IsoCountryCode
1090      * @throws NullPointerException if type is null
1091      * @return a {@code Set} of ISO country codes for the specified type.
1092      * @since 9
1093      */
1094     public static Set<String> getISOCountries(IsoCountryCode type) {
1095         Objects.requireNonNull(type);
1096         return IsoCountryCode.retrieveISOCountryCodes(type);
1097     }
1098 
1099     /**
1100      * Returns a list of all 2-letter language codes defined in ISO 639.
1101      * Can be used to create Locales.
1102      * <p>
1103      * <b>Note:</b>
1104      * <ul>
1105      * <li>ISO 639 is not a stable standard&mdash; some languages' codes have changed.
1106      * The list this function returns includes both the new and the old codes for the
1107      * languages whose codes have changed.
1108      * <li>The <code>Locale</code> class also supports language codes up to
1109      * 8 characters in length.  Therefore, the list returned by this method does
1110      * not contain ALL valid codes that can be used to create Locales.
1111      * </ul>
1112      *
1113      * @return An array of ISO 639 two-letter language codes.
1114      */
1115     public static String[] getISOLanguages() {
1116         if (isoLanguages == null) {
1117             isoLanguages = getISO2Table(LocaleISOData.isoLanguageTable);
1118         }
1119         String[] result = new String[isoLanguages.length];
1120         System.arraycopy(isoLanguages, 0, result, 0, isoLanguages.length);
1121         return result;
1122     }
1123 
1124     private static String[] getISO2Table(String table) {
1125         int len = table.length() / 5;
1126         String[] isoTable = new String[len];
1127         for (int i = 0, j = 0; i < len; i++, j += 5) {
1128             isoTable[i] = table.substring(j, j + 2);
1129         }
1130         return isoTable;
1131     }
1132 
1133     /**
1134      * Returns the language code of this Locale.
1135      *
1136      * <p><b>Note:</b> ISO 639 is not a stable standard&mdash; some languages' codes have changed.
1137      * Locale's constructor recognizes both the new and the old codes for the languages
1138      * whose codes have changed, but this function always returns the old code.  If you
1139      * want to check for a specific language whose code has changed, don't do
1140      * <pre>
1141      * if (locale.getLanguage().equals("he")) // BAD!
1142      *    ...
1143      * </pre>
1144      * Instead, do
1145      * <pre>
1146      * if (locale.getLanguage().equals(new Locale("he").getLanguage()))
1147      *    ...
1148      * </pre>
1149      * @return The language code, or the empty string if none is defined.
1150      * @see #getDisplayLanguage
1151      */
1152     public String getLanguage() {
1153         return baseLocale.getLanguage();
1154     }
1155 
1156     /**
1157      * Returns the script for this locale, which should
1158      * either be the empty string or an ISO 15924 4-letter script
1159      * code. The first letter is uppercase and the rest are
1160      * lowercase, for example, 'Latn', 'Cyrl'.
1161      *
1162      * @return The script code, or the empty string if none is defined.
1163      * @see #getDisplayScript
1164      * @since 1.7
1165      */
1166     public String getScript() {
1167         return baseLocale.getScript();
1168     }
1169 
1170     /**
1171      * Returns the country/region code for this locale, which should
1172      * either be the empty string, an uppercase ISO 3166 2-letter code,
1173      * or a UN M.49 3-digit code.
1174      *
1175      * @return The country/region code, or the empty string if none is defined.
1176      * @see #getDisplayCountry
1177      */
1178     public String getCountry() {
1179         return baseLocale.getRegion();
1180     }
1181 
1182     /**
1183      * Returns the variant code for this locale.
1184      *
1185      * @return The variant code, or the empty string if none is defined.
1186      * @see #getDisplayVariant
1187      */
1188     public String getVariant() {
1189         return baseLocale.getVariant();
1190     }
1191 
1192     /**
1193      * Returns {@code true} if this {@code Locale} has any <a href="#def_extensions">
1194      * extensions</a>.
1195      *
1196      * @return {@code true} if this {@code Locale} has any extensions
1197      * @since 1.8
1198      */
1199     public boolean hasExtensions() {
1200         return localeExtensions != null;
1201     }
1202 
1203     /**
1204      * Returns a copy of this {@code Locale} with no <a href="#def_extensions">
1205      * extensions</a>. If this {@code Locale} has no extensions, this {@code Locale}
1206      * is returned.
1207      *
1208      * @return a copy of this {@code Locale} with no extensions, or {@code this}
1209      *         if {@code this} has no extensions
1210      * @since 1.8
1211      */
1212     public Locale stripExtensions() {
1213         return hasExtensions() ? Locale.getInstance(baseLocale, null) : this;
1214     }
1215 
1216     /**
1217      * Returns the extension (or private use) value associated with
1218      * the specified key, or null if there is no extension
1219      * associated with the key. To be well-formed, the key must be one
1220      * of <code>[0-9A-Za-z]</code>. Keys are case-insensitive, so
1221      * for example 'z' and 'Z' represent the same extension.
1222      *
1223      * @param key the extension key
1224      * @return The extension, or null if this locale defines no
1225      * extension for the specified key.
1226      * @throws IllegalArgumentException if key is not well-formed
1227      * @see #PRIVATE_USE_EXTENSION
1228      * @see #UNICODE_LOCALE_EXTENSION
1229      * @since 1.7
1230      */
1231     public String getExtension(char key) {
1232         if (!LocaleExtensions.isValidKey(key)) {
1233             throw new IllegalArgumentException("Ill-formed extension key: " + key);
1234         }
1235         return hasExtensions() ? localeExtensions.getExtensionValue(key) : null;
1236     }
1237 
1238     /**
1239      * Returns the set of extension keys associated with this locale, or the
1240      * empty set if it has no extensions. The returned set is unmodifiable.
1241      * The keys will all be lower-case.
1242      *
1243      * @return The set of extension keys, or the empty set if this locale has
1244      * no extensions.
1245      * @since 1.7
1246      */
1247     public Set<Character> getExtensionKeys() {
1248         if (!hasExtensions()) {
1249             return Collections.emptySet();
1250         }
1251         return localeExtensions.getKeys();
1252     }
1253 
1254     /**
1255      * Returns the set of unicode locale attributes associated with
1256      * this locale, or the empty set if it has no attributes. The
1257      * returned set is unmodifiable.
1258      *
1259      * @return The set of attributes.
1260      * @since 1.7
1261      */
1262     public Set<String> getUnicodeLocaleAttributes() {
1263         if (!hasExtensions()) {
1264             return Collections.emptySet();
1265         }
1266         return localeExtensions.getUnicodeLocaleAttributes();
1267     }
1268 
1269     /**
1270      * Returns the Unicode locale type associated with the specified Unicode locale key
1271      * for this locale. Returns the empty string for keys that are defined with no type.
1272      * Returns null if the key is not defined. Keys are case-insensitive. The key must
1273      * be two alphanumeric characters ([0-9a-zA-Z]), or an IllegalArgumentException is
1274      * thrown.
1275      *
1276      * @param key the Unicode locale key
1277      * @return The Unicode locale type associated with the key, or null if the
1278      * locale does not define the key.
1279      * @throws IllegalArgumentException if the key is not well-formed
1280      * @throws NullPointerException if <code>key</code> is null
1281      * @since 1.7
1282      */
1283     public String getUnicodeLocaleType(String key) {
1284         if (!isUnicodeExtensionKey(key)) {
1285             throw new IllegalArgumentException("Ill-formed Unicode locale key: " + key);
1286         }
1287         return hasExtensions() ? localeExtensions.getUnicodeLocaleType(key) : null;
1288     }
1289 
1290     /**
1291      * Returns the set of Unicode locale keys defined by this locale, or the empty set if
1292      * this locale has none.  The returned set is immutable.  Keys are all lower case.
1293      *
1294      * @return The set of Unicode locale keys, or the empty set if this locale has
1295      * no Unicode locale keywords.
1296      * @since 1.7
1297      */
1298     public Set<String> getUnicodeLocaleKeys() {
1299         if (localeExtensions == null) {
1300             return Collections.emptySet();
1301         }
1302         return localeExtensions.getUnicodeLocaleKeys();
1303     }
1304 
1305     /**
1306      * Package locale method returning the Locale's BaseLocale,
1307      * used by ResourceBundle
1308      * @return base locale of this Locale
1309      */
1310     BaseLocale getBaseLocale() {
1311         return baseLocale;
1312     }
1313 
1314     /**
1315      * Package private method returning the Locale's LocaleExtensions,
1316      * used by ResourceBundle.
1317      * @return locale extensions of this Locale,
1318      *         or {@code null} if no extensions are defined
1319      */
1320      LocaleExtensions getLocaleExtensions() {
1321          return localeExtensions;
1322      }
1323 
1324     /**
1325      * Returns a string representation of this <code>Locale</code>
1326      * object, consisting of language, country, variant, script,
1327      * and extensions as below:
1328      * <blockquote>
1329      * language + "_" + country + "_" + (variant + "_#" | "#") + script + "_" + extensions
1330      * </blockquote>
1331      *
1332      * Language is always lower case, country is always upper case, script is always title
1333      * case, and extensions are always lower case.  Extensions and private use subtags
1334      * will be in canonical order as explained in {@link #toLanguageTag}.
1335      *
1336      * <p>When the locale has neither script nor extensions, the result is the same as in
1337      * Java 6 and prior.
1338      *
1339      * <p>If both the language and country fields are missing, this function will return
1340      * the empty string, even if the variant, script, or extensions field is present (you
1341      * can't have a locale with just a variant, the variant must accompany a well-formed
1342      * language or country code).
1343      *
1344      * <p>If script or extensions are present and variant is missing, no underscore is
1345      * added before the "#".
1346      *
1347      * <p>This behavior is designed to support debugging and to be compatible with
1348      * previous uses of <code>toString</code> that expected language, country, and variant
1349      * fields only.  To represent a Locale as a String for interchange purposes, use
1350      * {@link #toLanguageTag}.
1351      *
1352      * <p>Examples: <ul>
1353      * <li>{@code en}</li>
1354      * <li>{@code de_DE}</li>
1355      * <li>{@code _GB}</li>
1356      * <li>{@code en_US_WIN}</li>
1357      * <li>{@code de__POSIX}</li>
1358      * <li>{@code zh_CN_#Hans}</li>
1359      * <li>{@code zh_TW_#Hant_x-java}</li>
1360      * <li>{@code th_TH_TH_#u-nu-thai}</li></ul>
1361      *
1362      * @return A string representation of the Locale, for debugging.
1363      * @see #getDisplayName
1364      * @see #toLanguageTag
1365      */
1366     @Override
1367     public final String toString() {
1368         boolean l = (baseLocale.getLanguage().length() != 0);
1369         boolean s = (baseLocale.getScript().length() != 0);
1370         boolean r = (baseLocale.getRegion().length() != 0);
1371         boolean v = (baseLocale.getVariant().length() != 0);
1372         boolean e = (localeExtensions != null && localeExtensions.getID().length() != 0);
1373 
1374         StringBuilder result = new StringBuilder(baseLocale.getLanguage());
1375         if (r || (l && (v || s || e))) {
1376             result.append('_')
1377                 .append(baseLocale.getRegion()); // This may just append '_'
1378         }
1379         if (v && (l || r)) {
1380             result.append('_')
1381                 .append(baseLocale.getVariant());
1382         }
1383 
1384         if (s && (l || r)) {
1385             result.append("_#")
1386                 .append(baseLocale.getScript());
1387         }
1388 
1389         if (e && (l || r)) {
1390             result.append('_');
1391             if (!s) {
1392                 result.append('#');
1393             }
1394             result.append(localeExtensions.getID());
1395         }
1396 
1397         return result.toString();
1398     }
1399 
1400     /**
1401      * Returns a well-formed IETF BCP 47 language tag representing
1402      * this locale.
1403      *
1404      * <p>If this <code>Locale</code> has a language, country, or
1405      * variant that does not satisfy the IETF BCP 47 language tag
1406      * syntax requirements, this method handles these fields as
1407      * described below:
1408      *
1409      * <p><b>Language:</b> If language is empty, or not <a
1410      * href="#def_language" >well-formed</a> (for example "a" or
1411      * "e2"), it will be emitted as "und" (Undetermined).
1412      *
1413      * <p><b>Country:</b> If country is not <a
1414      * href="#def_region">well-formed</a> (for example "12" or "USA"),
1415      * it will be omitted.
1416      *
1417      * <p><b>Variant:</b> If variant <b>is</b> <a
1418      * href="#def_variant">well-formed</a>, each sub-segment
1419      * (delimited by '-' or '_') is emitted as a subtag.  Otherwise:
1420      * <ul>
1421      *
1422      * <li>if all sub-segments match <code>[0-9a-zA-Z]{1,8}</code>
1423      * (for example "WIN" or "Oracle_JDK_Standard_Edition"), the first
1424      * ill-formed sub-segment and all following will be appended to
1425      * the private use subtag.  The first appended subtag will be
1426      * "lvariant", followed by the sub-segments in order, separated by
1427      * hyphen. For example, "x-lvariant-WIN",
1428      * "Oracle-x-lvariant-JDK-Standard-Edition".
1429      *
1430      * <li>if any sub-segment does not match
1431      * <code>[0-9a-zA-Z]{1,8}</code>, the variant will be truncated
1432      * and the problematic sub-segment and all following sub-segments
1433      * will be omitted.  If the remainder is non-empty, it will be
1434      * emitted as a private use subtag as above (even if the remainder
1435      * turns out to be well-formed).  For example,
1436      * "Solaris_isjustthecoolestthing" is emitted as
1437      * "x-lvariant-Solaris", not as "solaris".</li></ul>
1438      *
1439      * <p><b>Special Conversions:</b> Java supports some old locale
1440      * representations, including deprecated ISO language codes,
1441      * for compatibility. This method performs the following
1442      * conversions:
1443      * <ul>
1444      *
1445      * <li>Deprecated ISO language codes "iw", "ji", and "in" are
1446      * converted to "he", "yi", and "id", respectively.
1447      *
1448      * <li>A locale with language "no", country "NO", and variant
1449      * "NY", representing Norwegian Nynorsk (Norway), is converted
1450      * to a language tag "nn-NO".</li></ul>
1451      *
1452      * <p><b>Note:</b> Although the language tag created by this
1453      * method is well-formed (satisfies the syntax requirements
1454      * defined by the IETF BCP 47 specification), it is not
1455      * necessarily a valid BCP 47 language tag.  For example,
1456      * <pre>
1457      *   new Locale("xx", "YY").toLanguageTag();</pre>
1458      *
1459      * will return "xx-YY", but the language subtag "xx" and the
1460      * region subtag "YY" are invalid because they are not registered
1461      * in the IANA Language Subtag Registry.
1462      *
1463      * @return a BCP47 language tag representing the locale
1464      * @see #forLanguageTag(String)
1465      * @since 1.7
1466      */
1467     public String toLanguageTag() {
1468         if (languageTag != null) {
1469             return languageTag;
1470         }
1471 
1472         LanguageTag tag = LanguageTag.parseLocale(baseLocale, localeExtensions);
1473         StringBuilder buf = new StringBuilder();
1474 
1475         String subtag = tag.getLanguage();
1476         if (subtag.length() > 0) {
1477             buf.append(LanguageTag.canonicalizeLanguage(subtag));
1478         }
1479 
1480         subtag = tag.getScript();
1481         if (subtag.length() > 0) {
1482             buf.append(LanguageTag.SEP);
1483             buf.append(LanguageTag.canonicalizeScript(subtag));
1484         }
1485 
1486         subtag = tag.getRegion();
1487         if (subtag.length() > 0) {
1488             buf.append(LanguageTag.SEP);
1489             buf.append(LanguageTag.canonicalizeRegion(subtag));
1490         }
1491 
1492         List<String>subtags = tag.getVariants();
1493         for (String s : subtags) {
1494             buf.append(LanguageTag.SEP);
1495             // preserve casing
1496             buf.append(s);
1497         }
1498 
1499         subtags = tag.getExtensions();
1500         for (String s : subtags) {
1501             buf.append(LanguageTag.SEP);
1502             buf.append(LanguageTag.canonicalizeExtension(s));
1503         }
1504 
1505         subtag = tag.getPrivateuse();
1506         if (subtag.length() > 0) {
1507             if (buf.length() > 0) {
1508                 buf.append(LanguageTag.SEP);
1509             }
1510             buf.append(LanguageTag.PRIVATEUSE).append(LanguageTag.SEP);
1511             // preserve casing
1512             buf.append(subtag);
1513         }
1514 
1515         String langTag = buf.toString();
1516         synchronized (this) {
1517             if (languageTag == null) {
1518                 languageTag = langTag;
1519             }
1520         }
1521         return languageTag;
1522     }
1523 
1524     /**
1525      * Returns a locale for the specified IETF BCP 47 language tag string.
1526      *
1527      * <p>If the specified language tag contains any ill-formed subtags,
1528      * the first such subtag and all following subtags are ignored.  Compare
1529      * to {@link Locale.Builder#setLanguageTag} which throws an exception
1530      * in this case.
1531      *
1532      * <p>The following <b>conversions</b> are performed:<ul>
1533      *
1534      * <li>The language code "und" is mapped to language "".
1535      *
1536      * <li>The language codes "he", "yi", and "id" are mapped to "iw",
1537      * "ji", and "in" respectively. (This is the same canonicalization
1538      * that's done in Locale's constructors.)
1539      *
1540      * <li>The portion of a private use subtag prefixed by "lvariant",
1541      * if any, is removed and appended to the variant field in the
1542      * result locale (without case normalization).  If it is then
1543      * empty, the private use subtag is discarded:
1544      *
1545      * <pre>
1546      *     Locale loc;
1547      *     loc = Locale.forLanguageTag("en-US-x-lvariant-POSIX");
1548      *     loc.getVariant(); // returns "POSIX"
1549      *     loc.getExtension('x'); // returns null
1550      *
1551      *     loc = Locale.forLanguageTag("de-POSIX-x-URP-lvariant-Abc-Def");
1552      *     loc.getVariant(); // returns "POSIX_Abc_Def"
1553      *     loc.getExtension('x'); // returns "urp"
1554      * </pre>
1555      *
1556      * <li>When the languageTag argument contains an extlang subtag,
1557      * the first such subtag is used as the language, and the primary
1558      * language subtag and other extlang subtags are ignored:
1559      *
1560      * <pre>
1561      *     Locale.forLanguageTag("ar-aao").getLanguage(); // returns "aao"
1562      *     Locale.forLanguageTag("en-abc-def-us").toString(); // returns "abc_US"
1563      * </pre>
1564      *
1565      * <li>Case is normalized except for variant tags, which are left
1566      * unchanged.  Language is normalized to lower case, script to
1567      * title case, country to upper case, and extensions to lower
1568      * case.
1569      *
1570      * <li>If, after processing, the locale would exactly match either
1571      * ja_JP_JP or th_TH_TH with no extensions, the appropriate
1572      * extensions are added as though the constructor had been called:
1573      *
1574      * <pre>
1575      *    Locale.forLanguageTag("ja-JP-x-lvariant-JP").toLanguageTag();
1576      *    // returns "ja-JP-u-ca-japanese-x-lvariant-JP"
1577      *    Locale.forLanguageTag("th-TH-x-lvariant-TH").toLanguageTag();
1578      *    // returns "th-TH-u-nu-thai-x-lvariant-TH"
1579      * </pre></ul>
1580      *
1581      * <p>This implements the 'Language-Tag' production of BCP47, and
1582      * so supports grandfathered (regular and irregular) as well as
1583      * private use language tags.  Stand alone private use tags are
1584      * represented as empty language and extension 'x-whatever',
1585      * and grandfathered tags are converted to their canonical replacements
1586      * where they exist.
1587      *
1588      * <p>Grandfathered tags with canonical replacements are as follows:
1589      *
1590      * <table class="altrows">
1591      * <caption style="display:none">Grandfathered tags with canonical replacements</caption>
1592      * <thead style="text-align:center">
1593      * <tr><th style="padding: 0 2px">grandfathered tag</th><th style="padding: 0 2px">modern replacement</th></tr>
1594      * </thead>
1595      * <tbody style="text-align:center">
1596      * <tr><td>art-lojban</td><td>jbo</td></tr>
1597      * <tr><td>i-ami</td><td>ami</td></tr>
1598      * <tr><td>i-bnn</td><td>bnn</td></tr>
1599      * <tr><td>i-hak</td><td>hak</td></tr>
1600      * <tr><td>i-klingon</td><td>tlh</td></tr>
1601      * <tr><td>i-lux</td><td>lb</td></tr>
1602      * <tr><td>i-navajo</td><td>nv</td></tr>
1603      * <tr><td>i-pwn</td><td>pwn</td></tr>
1604      * <tr><td>i-tao</td><td>tao</td></tr>
1605      * <tr><td>i-tay</td><td>tay</td></tr>
1606      * <tr><td>i-tsu</td><td>tsu</td></tr>
1607      * <tr><td>no-bok</td><td>nb</td></tr>
1608      * <tr><td>no-nyn</td><td>nn</td></tr>
1609      * <tr><td>sgn-BE-FR</td><td>sfb</td></tr>
1610      * <tr><td>sgn-BE-NL</td><td>vgt</td></tr>
1611      * <tr><td>sgn-CH-DE</td><td>sgg</td></tr>
1612      * <tr><td>zh-guoyu</td><td>cmn</td></tr>
1613      * <tr><td>zh-hakka</td><td>hak</td></tr>
1614      * <tr><td>zh-min-nan</td><td>nan</td></tr>
1615      * <tr><td>zh-xiang</td><td>hsn</td></tr>
1616      * </tbody>
1617      * </table>
1618      *
1619      * <p>Grandfathered tags with no modern replacement will be
1620      * converted as follows:
1621      *
1622      * <table class="altrows">
1623      * <caption style="display:none">Grandfathered tags with no modern replacement</caption>
1624      * <thead style="text-align:center">
1625      * <tr><th style="padding: 0 2px">grandfathered tag</th><th style="padding: 0 2px">converts to</th></tr>
1626      * </thead>
1627      * <tbody style="text-align:center">
1628      * <tr><td>cel-gaulish</td><td>xtg-x-cel-gaulish</td></tr>
1629      * <tr><td>en-GB-oed</td><td>en-GB-x-oed</td></tr>
1630      * <tr><td>i-default</td><td>en-x-i-default</td></tr>
1631      * <tr><td>i-enochian</td><td>und-x-i-enochian</td></tr>
1632      * <tr><td>i-mingo</td><td>see-x-i-mingo</td></tr>
1633      * <tr><td>zh-min</td><td>nan-x-zh-min</td></tr>
1634      * </tbody>
1635      * </table>
1636      *
1637      * <p>For a list of all grandfathered tags, see the
1638      * IANA Language Subtag Registry (search for "Type: grandfathered").
1639      *
1640      * <p><b>Note</b>: there is no guarantee that <code>toLanguageTag</code>
1641      * and <code>forLanguageTag</code> will round-trip.
1642      *
1643      * @param languageTag the language tag
1644      * @return The locale that best represents the language tag.
1645      * @throws NullPointerException if <code>languageTag</code> is <code>null</code>
1646      * @see #toLanguageTag()
1647      * @see java.util.Locale.Builder#setLanguageTag(String)
1648      * @since 1.7
1649      */
1650     public static Locale forLanguageTag(String languageTag) {
1651         LanguageTag tag = LanguageTag.parse(languageTag, null);
1652         InternalLocaleBuilder bldr = new InternalLocaleBuilder();
1653         bldr.setLanguageTag(tag);
1654         BaseLocale base = bldr.getBaseLocale();
1655         LocaleExtensions exts = bldr.getLocaleExtensions();
1656         if (exts == null && base.getVariant().length() > 0) {
1657             exts = getCompatibilityExtensions(base.getLanguage(), base.getScript(),
1658                                               base.getRegion(), base.getVariant());
1659         }
1660         return getInstance(base, exts);
1661     }
1662 
1663     /**
1664      * Returns a three-letter abbreviation of this locale's language.
1665      * If the language matches an ISO 639-1 two-letter code, the
1666      * corresponding ISO 639-2/T three-letter lowercase code is
1667      * returned.  The ISO 639-2 language codes can be found on-line,
1668      * see "Codes for the Representation of Names of Languages Part 2:
1669      * Alpha-3 Code".  If the locale specifies a three-letter
1670      * language, the language is returned as is.  If the locale does
1671      * not specify a language the empty string is returned.
1672      *
1673      * @return A three-letter abbreviation of this locale's language.
1674      * @exception MissingResourceException Throws MissingResourceException if
1675      * three-letter language abbreviation is not available for this locale.
1676      */
1677     public String getISO3Language() throws MissingResourceException {
1678         String lang = baseLocale.getLanguage();
1679         if (lang.length() == 3) {
1680             return lang;
1681         }
1682 
1683         String language3 = getISO3Code(lang, LocaleISOData.isoLanguageTable);
1684         if (language3 == null) {
1685             throw new MissingResourceException("Couldn't find 3-letter language code for "
1686                     + lang, "FormatData_" + toString(), "ShortLanguage");
1687         }
1688         return language3;
1689     }
1690 
1691     /**
1692      * Returns a three-letter abbreviation for this locale's country.
1693      * If the country matches an ISO 3166-1 alpha-2 code, the
1694      * corresponding ISO 3166-1 alpha-3 uppercase code is returned.
1695      * If the locale doesn't specify a country, this will be the empty
1696      * string.
1697      *
1698      * <p>The ISO 3166-1 codes can be found on-line.
1699      *
1700      * @return A three-letter abbreviation of this locale's country.
1701      * @exception MissingResourceException Throws MissingResourceException if the
1702      * three-letter country abbreviation is not available for this locale.
1703      */
1704     public String getISO3Country() throws MissingResourceException {
1705         String country3 = getISO3Code(baseLocale.getRegion(), LocaleISOData.isoCountryTable);
1706         if (country3 == null) {
1707             throw new MissingResourceException("Couldn't find 3-letter country code for "
1708                     + baseLocale.getRegion(), "FormatData_" + toString(), "ShortCountry");
1709         }
1710         return country3;
1711     }
1712 
1713     private static String getISO3Code(String iso2Code, String table) {
1714         int codeLength = iso2Code.length();
1715         if (codeLength == 0) {
1716             return "";
1717         }
1718 
1719         int tableLength = table.length();
1720         int index = tableLength;
1721         if (codeLength == 2) {
1722             char c1 = iso2Code.charAt(0);
1723             char c2 = iso2Code.charAt(1);
1724             for (index = 0; index < tableLength; index += 5) {
1725                 if (table.charAt(index) == c1
1726                     && table.charAt(index + 1) == c2) {
1727                     break;
1728                 }
1729             }
1730         }
1731         return index < tableLength ? table.substring(index + 2, index + 5) : null;
1732     }
1733 
1734     /**
1735      * Returns a name for the locale's language that is appropriate for display to the
1736      * user.
1737      * If possible, the name returned will be localized for the default
1738      * {@link Locale.Category#DISPLAY DISPLAY} locale.
1739      * For example, if the locale is fr_FR and the default
1740      * {@link Locale.Category#DISPLAY DISPLAY} locale
1741      * is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and
1742      * the default {@link Locale.Category#DISPLAY DISPLAY} locale is fr_FR,
1743      * getDisplayLanguage() will return "anglais".
1744      * If the name returned cannot be localized for the default
1745      * {@link Locale.Category#DISPLAY DISPLAY} locale,
1746      * (say, we don't have a Japanese name for Croatian),
1747      * this function falls back on the English name, and uses the ISO code as a last-resort
1748      * value.  If the locale doesn't specify a language, this function returns the empty string.
1749      *
1750      * @return The name of the display language.
1751      */
1752     public final String getDisplayLanguage() {
1753         return getDisplayLanguage(getDefault(Category.DISPLAY));
1754     }
1755 
1756     /**
1757      * Returns a name for the locale's language that is appropriate for display to the
1758      * user.
1759      * If possible, the name returned will be localized according to inLocale.
1760      * For example, if the locale is fr_FR and inLocale
1761      * is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and
1762      * inLocale is fr_FR, getDisplayLanguage() will return "anglais".
1763      * If the name returned cannot be localized according to inLocale,
1764      * (say, we don't have a Japanese name for Croatian),
1765      * this function falls back on the English name, and finally
1766      * on the ISO code as a last-resort value.  If the locale doesn't specify a language,
1767      * this function returns the empty string.
1768      *
1769      * @param inLocale The locale for which to retrieve the display language.
1770      * @return The name of the display language appropriate to the given locale.
1771      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
1772      */
1773     public String getDisplayLanguage(Locale inLocale) {
1774         return getDisplayString(baseLocale.getLanguage(), inLocale, DISPLAY_LANGUAGE);
1775     }
1776 
1777     /**
1778      * Returns a name for the locale's script that is appropriate for display to
1779      * the user. If possible, the name will be localized for the default
1780      * {@link Locale.Category#DISPLAY DISPLAY} locale.  Returns
1781      * the empty string if this locale doesn't specify a script code.
1782      *
1783      * @return the display name of the script code for the current default
1784      *     {@link Locale.Category#DISPLAY DISPLAY} locale
1785      * @since 1.7
1786      */
1787     public String getDisplayScript() {
1788         return getDisplayScript(getDefault(Category.DISPLAY));
1789     }
1790 
1791     /**
1792      * Returns a name for the locale's script that is appropriate
1793      * for display to the user. If possible, the name will be
1794      * localized for the given locale. Returns the empty string if
1795      * this locale doesn't specify a script code.
1796      *
1797      * @param inLocale The locale for which to retrieve the display script.
1798      * @return the display name of the script code for the current default
1799      * {@link Locale.Category#DISPLAY DISPLAY} locale
1800      * @throws NullPointerException if <code>inLocale</code> is <code>null</code>
1801      * @since 1.7
1802      */
1803     public String getDisplayScript(Locale inLocale) {
1804         return getDisplayString(baseLocale.getScript(), inLocale, DISPLAY_SCRIPT);
1805     }
1806 
1807     /**
1808      * Returns a name for the locale's country that is appropriate for display to the
1809      * user.
1810      * If possible, the name returned will be localized for the default
1811      * {@link Locale.Category#DISPLAY DISPLAY} locale.
1812      * For example, if the locale is fr_FR and the default
1813      * {@link Locale.Category#DISPLAY DISPLAY} locale
1814      * is en_US, getDisplayCountry() will return "France"; if the locale is en_US and
1815      * the default {@link Locale.Category#DISPLAY DISPLAY} locale is fr_FR,
1816      * getDisplayCountry() will return "Etats-Unis".
1817      * If the name returned cannot be localized for the default
1818      * {@link Locale.Category#DISPLAY DISPLAY} locale,
1819      * (say, we don't have a Japanese name for Croatia),
1820      * this function falls back on the English name, and uses the ISO code as a last-resort
1821      * value.  If the locale doesn't specify a country, this function returns the empty string.
1822      *
1823      * @return The name of the country appropriate to the locale.
1824      */
1825     public final String getDisplayCountry() {
1826         return getDisplayCountry(getDefault(Category.DISPLAY));
1827     }
1828 
1829     /**
1830      * Returns a name for the locale's country that is appropriate for display to the
1831      * user.
1832      * If possible, the name returned will be localized according to inLocale.
1833      * For example, if the locale is fr_FR and inLocale
1834      * is en_US, getDisplayCountry() will return "France"; if the locale is en_US and
1835      * inLocale is fr_FR, getDisplayCountry() will return "Etats-Unis".
1836      * If the name returned cannot be localized according to inLocale.
1837      * (say, we don't have a Japanese name for Croatia),
1838      * this function falls back on the English name, and finally
1839      * on the ISO code as a last-resort value.  If the locale doesn't specify a country,
1840      * this function returns the empty string.
1841      *
1842      * @param inLocale The locale for which to retrieve the display country.
1843      * @return The name of the country appropriate to the given locale.
1844      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
1845      */
1846     public String getDisplayCountry(Locale inLocale) {
1847         return getDisplayString(baseLocale.getRegion(), inLocale, DISPLAY_COUNTRY);
1848     }
1849 
1850     private String getDisplayString(String code, Locale inLocale, int type) {
1851         if (code.length() == 0) {
1852             return "";
1853         }
1854 
1855         if (inLocale == null) {
1856             throw new NullPointerException();
1857         }
1858 
1859         LocaleServiceProviderPool pool =
1860             LocaleServiceProviderPool.getPool(LocaleNameProvider.class);
1861         String key = (type == DISPLAY_VARIANT ? "%%"+code : code);
1862         String result = pool.getLocalizedObject(
1863                                 LocaleNameGetter.INSTANCE,
1864                                 inLocale, key, type, code);
1865             if (result != null) {
1866                 return result;
1867             }
1868 
1869         return code;
1870     }
1871 
1872     /**
1873      * Returns a name for the locale's variant code that is appropriate for display to the
1874      * user.  If possible, the name will be localized for the default
1875      * {@link Locale.Category#DISPLAY DISPLAY} locale.  If the locale
1876      * doesn't specify a variant code, this function returns the empty string.
1877      *
1878      * @return The name of the display variant code appropriate to the locale.
1879      */
1880     public final String getDisplayVariant() {
1881         return getDisplayVariant(getDefault(Category.DISPLAY));
1882     }
1883 
1884     /**
1885      * Returns a name for the locale's variant code that is appropriate for display to the
1886      * user.  If possible, the name will be localized for inLocale.  If the locale
1887      * doesn't specify a variant code, this function returns the empty string.
1888      *
1889      * @param inLocale The locale for which to retrieve the display variant code.
1890      * @return The name of the display variant code appropriate to the given locale.
1891      * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
1892      */
1893     public String getDisplayVariant(Locale inLocale) {
1894         if (baseLocale.getVariant().length() == 0)
1895             return "";
1896 
1897         LocaleResources lr = LocaleProviderAdapter.forJRE().getLocaleResources(inLocale);
1898 
1899         String names[] = getDisplayVariantArray(inLocale);
1900 
1901         // Get the localized patterns for formatting a list, and use
1902         // them to format the list.
1903         return formatList(names,
1904                           lr.getLocaleName("ListPattern"),
1905                           lr.getLocaleName("ListCompositionPattern"));
1906     }
1907 
1908     /**
1909      * Returns a name for the locale that is appropriate for display to the
1910      * user. This will be the values returned by getDisplayLanguage(),
1911      * getDisplayScript(), getDisplayCountry(), and getDisplayVariant() assembled
1912      * into a single string. The the non-empty values are used in order,
1913      * with the second and subsequent names in parentheses.  For example:
1914      * <blockquote>
1915      * language (script, country, variant)<br>
1916      * language (country)<br>
1917      * language (variant)<br>
1918      * script (country)<br>
1919      * country<br>
1920      * </blockquote>
1921      * depending on which fields are specified in the locale.  If the
1922      * language, script, country, and variant fields are all empty,
1923      * this function returns the empty string.
1924      *
1925      * @return The name of the locale appropriate to display.
1926      */
1927     public final String getDisplayName() {
1928         return getDisplayName(getDefault(Category.DISPLAY));
1929     }
1930 
1931     /**
1932      * Returns a name for the locale that is appropriate for display
1933      * to the user.  This will be the values returned by
1934      * getDisplayLanguage(), getDisplayScript(),getDisplayCountry(),
1935      * and getDisplayVariant() assembled into a single string.
1936      * The non-empty values are used in order,
1937      * with the second and subsequent names in parentheses.  For example:
1938      * <blockquote>
1939      * language (script, country, variant)<br>
1940      * language (country)<br>
1941      * language (variant)<br>
1942      * script (country)<br>
1943      * country<br>
1944      * </blockquote>
1945      * depending on which fields are specified in the locale.  If the
1946      * language, script, country, and variant fields are all empty,
1947      * this function returns the empty string.
1948      *
1949      * @param inLocale The locale for which to retrieve the display name.
1950      * @return The name of the locale appropriate to display.
1951      * @throws NullPointerException if <code>inLocale</code> is <code>null</code>
1952      */
1953     public String getDisplayName(Locale inLocale) {
1954         LocaleResources lr =  LocaleProviderAdapter.forJRE().getLocaleResources(inLocale);
1955 
1956         String languageName = getDisplayLanguage(inLocale);
1957         String scriptName = getDisplayScript(inLocale);
1958         String countryName = getDisplayCountry(inLocale);
1959         String[] variantNames = getDisplayVariantArray(inLocale);
1960 
1961         // Get the localized patterns for formatting a display name.
1962         String displayNamePattern = lr.getLocaleName("DisplayNamePattern");
1963         String listPattern = lr.getLocaleName("ListPattern");
1964         String listCompositionPattern = lr.getLocaleName("ListCompositionPattern");
1965 
1966         // The display name consists of a main name, followed by qualifiers.
1967         // Typically, the format is "MainName (Qualifier, Qualifier)" but this
1968         // depends on what pattern is stored in the display locale.
1969         String   mainName       = null;
1970         String[] qualifierNames = null;
1971 
1972         // The main name is the language, or if there is no language, the script,
1973         // then if no script, the country. If there is no language/script/country
1974         // (an anomalous situation) then the display name is simply the variant's
1975         // display name.
1976         if (languageName.length() == 0 && scriptName.length() == 0 && countryName.length() == 0) {
1977             if (variantNames.length == 0) {
1978                 return "";
1979             } else {
1980                 return formatList(variantNames, listPattern, listCompositionPattern);
1981             }
1982         }
1983         ArrayList<String> names = new ArrayList<>(4);
1984         if (languageName.length() != 0) {
1985             names.add(languageName);
1986         }
1987         if (scriptName.length() != 0) {
1988             names.add(scriptName);
1989         }
1990         if (countryName.length() != 0) {
1991             names.add(countryName);
1992         }
1993         if (variantNames.length != 0) {
1994             names.addAll(Arrays.asList(variantNames));
1995         }
1996 
1997         // The first one in the main name
1998         mainName = names.get(0);
1999 
2000         // Others are qualifiers
2001         int numNames = names.size();
2002         qualifierNames = (numNames > 1) ?
2003                 names.subList(1, numNames).toArray(new String[numNames - 1]) : new String[0];
2004 
2005         // Create an array whose first element is the number of remaining
2006         // elements.  This serves as a selector into a ChoiceFormat pattern from
2007         // the resource.  The second and third elements are the main name and
2008         // the qualifier; if there are no qualifiers, the third element is
2009         // unused by the format pattern.
2010         Object[] displayNames = {
2011             qualifierNames.length != 0 ? 2 : 1,
2012             mainName,
2013             // We could also just call formatList() and have it handle the empty
2014             // list case, but this is more efficient, and we want it to be
2015             // efficient since all the language-only locales will not have any
2016             // qualifiers.
2017             qualifierNames.length != 0 ? formatList(qualifierNames, listPattern, listCompositionPattern) : null
2018         };
2019 
2020         if (displayNamePattern != null) {
2021             return new MessageFormat(displayNamePattern).format(displayNames);
2022         }
2023         else {
2024             // If we cannot get the message format pattern, then we use a simple
2025             // hard-coded pattern.  This should not occur in practice unless the
2026             // installation is missing some core files (FormatData etc.).
2027             StringBuilder result = new StringBuilder();
2028             result.append((String)displayNames[1]);
2029             if (displayNames.length > 2) {
2030                 result.append(" (");
2031                 result.append((String)displayNames[2]);
2032                 result.append(')');
2033             }
2034             return result.toString();
2035         }
2036     }
2037 
2038     /**
2039      * Overrides Cloneable.
2040      */
2041     @Override
2042     public Object clone()
2043     {
2044         try {
2045             Locale that = (Locale)super.clone();
2046             return that;
2047         } catch (CloneNotSupportedException e) {
2048             throw new InternalError(e);
2049         }
2050     }
2051 
2052     /**
2053      * Override hashCode.
2054      * Since Locales are often used in hashtables, caches the value
2055      * for speed.
2056      */
2057     @Override
2058     public int hashCode() {
2059         int hc = hashCodeValue;
2060         if (hc == 0) {
2061             hc = baseLocale.hashCode();
2062             if (localeExtensions != null) {
2063                 hc ^= localeExtensions.hashCode();
2064             }
2065             hashCodeValue = hc;
2066         }
2067         return hc;
2068     }
2069 
2070     // Overrides
2071 
2072     /**
2073      * Returns true if this Locale is equal to another object.  A Locale is
2074      * deemed equal to another Locale with identical language, script, country,
2075      * variant and extensions, and unequal to all other objects.
2076      *
2077      * @return true if this Locale is equal to the specified object.
2078      */
2079     @Override
2080     public boolean equals(Object obj) {
2081         if (this == obj)                      // quick check
2082             return true;
2083         if (!(obj instanceof Locale))
2084             return false;
2085         BaseLocale otherBase = ((Locale)obj).baseLocale;
2086         if (!baseLocale.equals(otherBase)) {
2087             return false;
2088         }
2089         if (localeExtensions == null) {
2090             return ((Locale)obj).localeExtensions == null;
2091         }
2092         return localeExtensions.equals(((Locale)obj).localeExtensions);
2093     }
2094 
2095     // ================= privates =====================================
2096 
2097     private transient BaseLocale baseLocale;
2098     private transient LocaleExtensions localeExtensions;
2099 
2100     /**
2101      * Calculated hashcode
2102      */
2103     private transient volatile int hashCodeValue;
2104 
2105     private static volatile Locale defaultLocale = initDefault();
2106     private static volatile Locale defaultDisplayLocale;
2107     private static volatile Locale defaultFormatLocale;
2108 
2109     private transient volatile String languageTag;
2110 
2111     /**
2112      * Return an array of the display names of the variant.
2113      * @param bundle the ResourceBundle to use to get the display names
2114      * @return an array of display names, possible of zero length.
2115      */
2116     private String[] getDisplayVariantArray(Locale inLocale) {
2117         // Split the variant name into tokens separated by '_'.
2118         StringTokenizer tokenizer = new StringTokenizer(baseLocale.getVariant(), "_");
2119         String[] names = new String[tokenizer.countTokens()];
2120 
2121         // For each variant token, lookup the display name.  If
2122         // not found, use the variant name itself.
2123         for (int i=0; i<names.length; ++i) {
2124             names[i] = getDisplayString(tokenizer.nextToken(),
2125                                 inLocale, DISPLAY_VARIANT);
2126         }
2127 
2128         return names;
2129     }
2130 
2131     /**
2132      * Format a list using given pattern strings.
2133      * If either of the patterns is null, then a the list is
2134      * formatted by concatenation with the delimiter ','.
2135      * @param stringList the list of strings to be formatted.
2136      * @param listPattern should create a MessageFormat taking 0-3 arguments
2137      * and formatting them into a list.
2138      * @param listCompositionPattern should take 2 arguments
2139      * and is used by composeList.
2140      * @return a string representing the list.
2141      */
2142     private static String formatList(String[] stringList, String listPattern, String listCompositionPattern) {
2143         // If we have no list patterns, compose the list in a simple,
2144         // non-localized way.
2145         if (listPattern == null || listCompositionPattern == null) {
2146             StringJoiner sj = new StringJoiner(",");
2147             for (int i = 0; i < stringList.length; ++i) {
2148                 sj.add(stringList[i]);
2149             }
2150             return sj.toString();
2151         }
2152 
2153         // Compose the list down to three elements if necessary
2154         if (stringList.length > 3) {
2155             MessageFormat format = new MessageFormat(listCompositionPattern);
2156             stringList = composeList(format, stringList);
2157         }
2158 
2159         // Rebuild the argument list with the list length as the first element
2160         Object[] args = new Object[stringList.length + 1];
2161         System.arraycopy(stringList, 0, args, 1, stringList.length);
2162         args[0] = stringList.length;
2163 
2164         // Format it using the pattern in the resource
2165         MessageFormat format = new MessageFormat(listPattern);
2166         return format.format(args);
2167     }
2168 
2169     /**
2170      * Given a list of strings, return a list shortened to three elements.
2171      * Shorten it by applying the given format to the first two elements
2172      * recursively.
2173      * @param format a format which takes two arguments
2174      * @param list a list of strings
2175      * @return if the list is three elements or shorter, the same list;
2176      * otherwise, a new list of three elements.
2177      */
2178     private static String[] composeList(MessageFormat format, String[] list) {
2179         if (list.length <= 3) return list;
2180 
2181         // Use the given format to compose the first two elements into one
2182         String[] listItems = { list[0], list[1] };
2183         String newItem = format.format(listItems);
2184 
2185         // Form a new list one element shorter
2186         String[] newList = new String[list.length-1];
2187         System.arraycopy(list, 2, newList, 1, newList.length-1);
2188         newList[0] = newItem;
2189 
2190         // Recurse
2191         return composeList(format, newList);
2192     }
2193 
2194     // Duplicate of sun.util.locale.UnicodeLocaleExtension.isKey in order to
2195     // avoid its class loading.
2196     private static boolean isUnicodeExtensionKey(String s) {
2197         // 2alphanum
2198         return (s.length() == 2) && LocaleUtils.isAlphaNumericString(s);
2199     }
2200 
2201     /**
2202      * @serialField language    String
2203      *      language subtag in lower case. (See <a href="java/util/Locale.html#getLanguage()">getLanguage()</a>)
2204      * @serialField country     String
2205      *      country subtag in upper case. (See <a href="java/util/Locale.html#getCountry()">getCountry()</a>)
2206      * @serialField variant     String
2207      *      variant subtags separated by LOWLINE characters. (See <a href="java/util/Locale.html#getVariant()">getVariant()</a>)
2208      * @serialField hashcode    int
2209      *      deprecated, for forward compatibility only
2210      * @serialField script      String
2211      *      script subtag in title case (See <a href="java/util/Locale.html#getScript()">getScript()</a>)
2212      * @serialField extensions  String
2213      *      canonical representation of extensions, that is,
2214      *      BCP47 extensions in alphabetical order followed by
2215      *      BCP47 private use subtags, all in lower case letters
2216      *      separated by HYPHEN-MINUS characters.
2217      *      (See <a href="java/util/Locale.html#getExtensionKeys()">getExtensionKeys()</a>,
2218      *      <a href="java/util/Locale.html#getExtension(char)">getExtension(char)</a>)
2219      */
2220     private static final ObjectStreamField[] serialPersistentFields = {
2221         new ObjectStreamField("language", String.class),
2222         new ObjectStreamField("country", String.class),
2223         new ObjectStreamField("variant", String.class),
2224         new ObjectStreamField("hashcode", int.class),
2225         new ObjectStreamField("script", String.class),
2226         new ObjectStreamField("extensions", String.class),
2227     };
2228 
2229     /**
2230      * Serializes this <code>Locale</code> to the specified <code>ObjectOutputStream</code>.
2231      * @param out the <code>ObjectOutputStream</code> to write
2232      * @throws IOException
2233      * @since 1.7
2234      */
2235     private void writeObject(ObjectOutputStream out) throws IOException {
2236         ObjectOutputStream.PutField fields = out.putFields();
2237         fields.put("language", baseLocale.getLanguage());
2238         fields.put("script", baseLocale.getScript());
2239         fields.put("country", baseLocale.getRegion());
2240         fields.put("variant", baseLocale.getVariant());
2241         fields.put("extensions", localeExtensions == null ? "" : localeExtensions.getID());
2242         fields.put("hashcode", -1); // place holder just for backward support
2243         out.writeFields();
2244     }
2245 
2246     /**
2247      * Deserializes this <code>Locale</code>.
2248      * @param in the <code>ObjectInputStream</code> to read
2249      * @throws IOException
2250      * @throws ClassNotFoundException
2251      * @throws IllformedLocaleException
2252      * @since 1.7
2253      */
2254     private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
2255         ObjectInputStream.GetField fields = in.readFields();
2256         String language = (String)fields.get("language", "");
2257         String script = (String)fields.get("script", "");
2258         String country = (String)fields.get("country", "");
2259         String variant = (String)fields.get("variant", "");
2260         String extStr = (String)fields.get("extensions", "");
2261         baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), script, country, variant);
2262         if (extStr.length() > 0) {
2263             try {
2264                 InternalLocaleBuilder bldr = new InternalLocaleBuilder();
2265                 bldr.setExtensions(extStr);
2266                 localeExtensions = bldr.getLocaleExtensions();
2267             } catch (LocaleSyntaxException e) {
2268                 throw new IllformedLocaleException(e.getMessage());
2269             }
2270         } else {
2271             localeExtensions = null;
2272         }
2273     }
2274 
2275     /**
2276      * Returns a cached <code>Locale</code> instance equivalent to
2277      * the deserialized <code>Locale</code>. When serialized
2278      * language, country and variant fields read from the object data stream
2279      * are exactly "ja", "JP", "JP" or "th", "TH", "TH" and script/extensions
2280      * fields are empty, this method supplies <code>UNICODE_LOCALE_EXTENSION</code>
2281      * "ca"/"japanese" (calendar type is "japanese") or "nu"/"thai" (number script
2282      * type is "thai"). See <a href="Locale.html#special_cases_constructor">Special Cases</a>
2283      * for more information.
2284      *
2285      * @return an instance of <code>Locale</code> equivalent to
2286      * the deserialized <code>Locale</code>.
2287      * @throws java.io.ObjectStreamException
2288      */
2289     private Object readResolve() throws java.io.ObjectStreamException {
2290         return getInstance(baseLocale.getLanguage(), baseLocale.getScript(),
2291                 baseLocale.getRegion(), baseLocale.getVariant(), localeExtensions);
2292     }
2293 
2294     private static volatile String[] isoLanguages;
2295 
2296     private static volatile String[] isoCountries;
2297 
2298     private static String convertOldISOCodes(String language) {
2299         // we accept both the old and the new ISO codes for the languages whose ISO
2300         // codes have changed, but we always store the OLD code, for backward compatibility
2301         language = LocaleUtils.toLowerString(language).intern();
2302         if (language == "he") {
2303             return "iw";
2304         } else if (language == "yi") {
2305             return "ji";
2306         } else if (language == "id") {
2307             return "in";
2308         } else {
2309             return language;
2310         }
2311     }
2312 
2313     private static LocaleExtensions getCompatibilityExtensions(String language,
2314                                                                String script,
2315                                                                String country,
2316                                                                String variant) {
2317         LocaleExtensions extensions = null;
2318         // Special cases for backward compatibility support
2319         if (LocaleUtils.caseIgnoreMatch(language, "ja")
2320                 && script.length() == 0
2321                 && LocaleUtils.caseIgnoreMatch(country, "jp")
2322                 && "JP".equals(variant)) {
2323             // ja_JP_JP -> u-ca-japanese (calendar = japanese)
2324             extensions = LocaleExtensions.CALENDAR_JAPANESE;
2325         } else if (LocaleUtils.caseIgnoreMatch(language, "th")
2326                 && script.length() == 0
2327                 && LocaleUtils.caseIgnoreMatch(country, "th")
2328                 && "TH".equals(variant)) {
2329             // th_TH_TH -> u-nu-thai (numbersystem = thai)
2330             extensions = LocaleExtensions.NUMBER_THAI;
2331         }
2332         return extensions;
2333     }
2334 
2335     /**
2336      * Obtains a localized locale names from a LocaleNameProvider
2337      * implementation.
2338      */
2339     private static class LocaleNameGetter
2340         implements LocaleServiceProviderPool.LocalizedObjectGetter<LocaleNameProvider, String> {
2341         private static final LocaleNameGetter INSTANCE = new LocaleNameGetter();
2342 
2343         @Override
2344         public String getObject(LocaleNameProvider localeNameProvider,
2345                                 Locale locale,
2346                                 String key,
2347                                 Object... params) {
2348             assert params.length == 2;
2349             int type = (Integer)params[0];
2350             String code = (String)params[1];
2351 
2352             switch(type) {
2353             case DISPLAY_LANGUAGE:
2354                 return localeNameProvider.getDisplayLanguage(code, locale);
2355             case DISPLAY_COUNTRY:
2356                 return localeNameProvider.getDisplayCountry(code, locale);
2357             case DISPLAY_VARIANT:
2358                 return localeNameProvider.getDisplayVariant(code, locale);
2359             case DISPLAY_SCRIPT:
2360                 return localeNameProvider.getDisplayScript(code, locale);
2361             default:
2362                 assert false; // shouldn't happen
2363             }
2364 
2365             return null;
2366         }
2367     }
2368 
2369     /**
2370      * Enum for locale categories.  These locale categories are used to get/set
2371      * the default locale for the specific functionality represented by the
2372      * category.
2373      *
2374      * @see #getDefault(Locale.Category)
2375      * @see #setDefault(Locale.Category, Locale)
2376      * @since 1.7
2377      */
2378     public enum Category {
2379 
2380         /**
2381          * Category used to represent the default locale for
2382          * displaying user interfaces.
2383          */
2384         DISPLAY("user.language.display",
2385                 "user.script.display",
2386                 "user.country.display",
2387                 "user.variant.display"),
2388 
2389         /**
2390          * Category used to represent the default locale for
2391          * formatting dates, numbers, and/or currencies.
2392          */
2393         FORMAT("user.language.format",
2394                "user.script.format",
2395                "user.country.format",
2396                "user.variant.format");
2397 
2398         Category(String languageKey, String scriptKey, String countryKey, String variantKey) {
2399             this.languageKey = languageKey;
2400             this.scriptKey = scriptKey;
2401             this.countryKey = countryKey;
2402             this.variantKey = variantKey;
2403         }
2404 
2405         final String languageKey;
2406         final String scriptKey;
2407         final String countryKey;
2408         final String variantKey;
2409     }
2410 
2411     /**
2412      * <code>Builder</code> is used to build instances of <code>Locale</code>
2413      * from values configured by the setters.  Unlike the <code>Locale</code>
2414      * constructors, the <code>Builder</code> checks if a value configured by a
2415      * setter satisfies the syntax requirements defined by the <code>Locale</code>
2416      * class.  A <code>Locale</code> object created by a <code>Builder</code> is
2417      * well-formed and can be transformed to a well-formed IETF BCP 47 language tag
2418      * without losing information.
2419      *
2420      * <p><b>Note:</b> The <code>Locale</code> class does not provide any
2421      * syntactic restrictions on variant, while BCP 47 requires each variant
2422      * subtag to be 5 to 8 alphanumerics or a single numeric followed by 3
2423      * alphanumerics.  The method <code>setVariant</code> throws
2424      * <code>IllformedLocaleException</code> for a variant that does not satisfy
2425      * this restriction. If it is necessary to support such a variant, use a
2426      * Locale constructor.  However, keep in mind that a <code>Locale</code>
2427      * object created this way might lose the variant information when
2428      * transformed to a BCP 47 language tag.
2429      *
2430      * <p>The following example shows how to create a <code>Locale</code> object
2431      * with the <code>Builder</code>.
2432      * <blockquote>
2433      * <pre>
2434      *     Locale aLocale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build();
2435      * </pre>
2436      * </blockquote>
2437      *
2438      * <p>Builders can be reused; <code>clear()</code> resets all
2439      * fields to their default values.
2440      *
2441      * @see Locale#forLanguageTag
2442      * @since 1.7
2443      */
2444     public static final class Builder {
2445         private final InternalLocaleBuilder localeBuilder;
2446 
2447         /**
2448          * Constructs an empty Builder. The default value of all
2449          * fields, extensions, and private use information is the
2450          * empty string.
2451          */
2452         public Builder() {
2453             localeBuilder = new InternalLocaleBuilder();
2454         }
2455 
2456         /**
2457          * Resets the <code>Builder</code> to match the provided
2458          * <code>locale</code>.  Existing state is discarded.
2459          *
2460          * <p>All fields of the locale must be well-formed, see {@link Locale}.
2461          *
2462          * <p>Locales with any ill-formed fields cause
2463          * <code>IllformedLocaleException</code> to be thrown, except for the
2464          * following three cases which are accepted for compatibility
2465          * reasons:<ul>
2466          * <li>Locale("ja", "JP", "JP") is treated as "ja-JP-u-ca-japanese"
2467          * <li>Locale("th", "TH", "TH") is treated as "th-TH-u-nu-thai"
2468          * <li>Locale("no", "NO", "NY") is treated as "nn-NO"</ul>
2469          *
2470          * @param locale the locale
2471          * @return This builder.
2472          * @throws IllformedLocaleException if <code>locale</code> has
2473          * any ill-formed fields.
2474          * @throws NullPointerException if <code>locale</code> is null.
2475          */
2476         public Builder setLocale(Locale locale) {
2477             try {
2478                 localeBuilder.setLocale(locale.baseLocale, locale.localeExtensions);
2479             } catch (LocaleSyntaxException e) {
2480                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2481             }
2482             return this;
2483         }
2484 
2485         /**
2486          * Resets the Builder to match the provided IETF BCP 47
2487          * language tag.  Discards the existing state.  Null and the
2488          * empty string cause the builder to be reset, like {@link
2489          * #clear}.  Grandfathered tags (see {@link
2490          * Locale#forLanguageTag}) are converted to their canonical
2491          * form before being processed.  Otherwise, the language tag
2492          * must be well-formed (see {@link Locale}) or an exception is
2493          * thrown (unlike <code>Locale.forLanguageTag</code>, which
2494          * just discards ill-formed and following portions of the
2495          * tag).
2496          *
2497          * @param languageTag the language tag
2498          * @return This builder.
2499          * @throws IllformedLocaleException if <code>languageTag</code> is ill-formed
2500          * @see Locale#forLanguageTag(String)
2501          */
2502         public Builder setLanguageTag(String languageTag) {
2503             ParseStatus sts = new ParseStatus();
2504             LanguageTag tag = LanguageTag.parse(languageTag, sts);
2505             if (sts.isError()) {
2506                 throw new IllformedLocaleException(sts.getErrorMessage(), sts.getErrorIndex());
2507             }
2508             localeBuilder.setLanguageTag(tag);
2509             return this;
2510         }
2511 
2512         /**
2513          * Sets the language.  If <code>language</code> is the empty string or
2514          * null, the language in this <code>Builder</code> is removed.  Otherwise,
2515          * the language must be <a href="./Locale.html#def_language">well-formed</a>
2516          * or an exception is thrown.
2517          *
2518          * <p>The typical language value is a two or three-letter language
2519          * code as defined in ISO639.
2520          *
2521          * @param language the language
2522          * @return This builder.
2523          * @throws IllformedLocaleException if <code>language</code> is ill-formed
2524          */
2525         public Builder setLanguage(String language) {
2526             try {
2527                 localeBuilder.setLanguage(language);
2528             } catch (LocaleSyntaxException e) {
2529                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2530             }
2531             return this;
2532         }
2533 
2534         /**
2535          * Sets the script. If <code>script</code> is null or the empty string,
2536          * the script in this <code>Builder</code> is removed.
2537          * Otherwise, the script must be <a href="./Locale.html#def_script">well-formed</a> or an
2538          * exception is thrown.
2539          *
2540          * <p>The typical script value is a four-letter script code as defined by ISO 15924.
2541          *
2542          * @param script the script
2543          * @return This builder.
2544          * @throws IllformedLocaleException if <code>script</code> is ill-formed
2545          */
2546         public Builder setScript(String script) {
2547             try {
2548                 localeBuilder.setScript(script);
2549             } catch (LocaleSyntaxException e) {
2550                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2551             }
2552             return this;
2553         }
2554 
2555         /**
2556          * Sets the region.  If region is null or the empty string, the region
2557          * in this <code>Builder</code> is removed.  Otherwise,
2558          * the region must be <a href="./Locale.html#def_region">well-formed</a> or an
2559          * exception is thrown.
2560          *
2561          * <p>The typical region value is a two-letter ISO 3166 code or a
2562          * three-digit UN M.49 area code.
2563          *
2564          * <p>The country value in the <code>Locale</code> created by the
2565          * <code>Builder</code> is always normalized to upper case.
2566          *
2567          * @param region the region
2568          * @return This builder.
2569          * @throws IllformedLocaleException if <code>region</code> is ill-formed
2570          */
2571         public Builder setRegion(String region) {
2572             try {
2573                 localeBuilder.setRegion(region);
2574             } catch (LocaleSyntaxException e) {
2575                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2576             }
2577             return this;
2578         }
2579 
2580         /**
2581          * Sets the variant.  If variant is null or the empty string, the
2582          * variant in this <code>Builder</code> is removed.  Otherwise, it
2583          * must consist of one or more <a href="./Locale.html#def_variant">well-formed</a>
2584          * subtags, or an exception is thrown.
2585          *
2586          * <p><b>Note:</b> This method checks if <code>variant</code>
2587          * satisfies the IETF BCP 47 variant subtag's syntax requirements,
2588          * and normalizes the value to lowercase letters.  However,
2589          * the <code>Locale</code> class does not impose any syntactic
2590          * restriction on variant, and the variant value in
2591          * <code>Locale</code> is case sensitive.  To set such a variant,
2592          * use a Locale constructor.
2593          *
2594          * @param variant the variant
2595          * @return This builder.
2596          * @throws IllformedLocaleException if <code>variant</code> is ill-formed
2597          */
2598         public Builder setVariant(String variant) {
2599             try {
2600                 localeBuilder.setVariant(variant);
2601             } catch (LocaleSyntaxException e) {
2602                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2603             }
2604             return this;
2605         }
2606 
2607         /**
2608          * Sets the extension for the given key. If the value is null or the
2609          * empty string, the extension is removed.  Otherwise, the extension
2610          * must be <a href="./Locale.html#def_extensions">well-formed</a> or an exception
2611          * is thrown.
2612          *
2613          * <p><b>Note:</b> The key {@link Locale#UNICODE_LOCALE_EXTENSION
2614          * UNICODE_LOCALE_EXTENSION} ('u') is used for the Unicode locale extension.
2615          * Setting a value for this key replaces any existing Unicode locale key/type
2616          * pairs with those defined in the extension.
2617          *
2618          * <p><b>Note:</b> The key {@link Locale#PRIVATE_USE_EXTENSION
2619          * PRIVATE_USE_EXTENSION} ('x') is used for the private use code. To be
2620          * well-formed, the value for this key needs only to have subtags of one to
2621          * eight alphanumeric characters, not two to eight as in the general case.
2622          *
2623          * @param key the extension key
2624          * @param value the extension value
2625          * @return This builder.
2626          * @throws IllformedLocaleException if <code>key</code> is illegal
2627          * or <code>value</code> is ill-formed
2628          * @see #setUnicodeLocaleKeyword(String, String)
2629          */
2630         public Builder setExtension(char key, String value) {
2631             try {
2632                 localeBuilder.setExtension(key, value);
2633             } catch (LocaleSyntaxException e) {
2634                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2635             }
2636             return this;
2637         }
2638 
2639         /**
2640          * Sets the Unicode locale keyword type for the given key.  If the type
2641          * is null, the Unicode keyword is removed.  Otherwise, the key must be
2642          * non-null and both key and type must be <a
2643          * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
2644          * is thrown.
2645          *
2646          * <p>Keys and types are converted to lower case.
2647          *
2648          * <p><b>Note</b>:Setting the 'u' extension via {@link #setExtension}
2649          * replaces all Unicode locale keywords with those defined in the
2650          * extension.
2651          *
2652          * @param key the Unicode locale key
2653          * @param type the Unicode locale type
2654          * @return This builder.
2655          * @throws IllformedLocaleException if <code>key</code> or <code>type</code>
2656          * is ill-formed
2657          * @throws NullPointerException if <code>key</code> is null
2658          * @see #setExtension(char, String)
2659          */
2660         public Builder setUnicodeLocaleKeyword(String key, String type) {
2661             try {
2662                 localeBuilder.setUnicodeLocaleKeyword(key, type);
2663             } catch (LocaleSyntaxException e) {
2664                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2665             }
2666             return this;
2667         }
2668 
2669         /**
2670          * Adds a unicode locale attribute, if not already present, otherwise
2671          * has no effect.  The attribute must not be null and must be <a
2672          * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
2673          * is thrown.
2674          *
2675          * @param attribute the attribute
2676          * @return This builder.
2677          * @throws NullPointerException if <code>attribute</code> is null
2678          * @throws IllformedLocaleException if <code>attribute</code> is ill-formed
2679          * @see #setExtension(char, String)
2680          */
2681         public Builder addUnicodeLocaleAttribute(String attribute) {
2682             try {
2683                 localeBuilder.addUnicodeLocaleAttribute(attribute);
2684             } catch (LocaleSyntaxException e) {
2685                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2686             }
2687             return this;
2688         }
2689 
2690         /**
2691          * Removes a unicode locale attribute, if present, otherwise has no
2692          * effect.  The attribute must not be null and must be <a
2693          * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
2694          * is thrown.
2695          *
2696          * <p>Attribute comparison for removal is case-insensitive.
2697          *
2698          * @param attribute the attribute
2699          * @return This builder.
2700          * @throws NullPointerException if <code>attribute</code> is null
2701          * @throws IllformedLocaleException if <code>attribute</code> is ill-formed
2702          * @see #setExtension(char, String)
2703          */
2704         public Builder removeUnicodeLocaleAttribute(String attribute) {
2705             try {
2706                 localeBuilder.removeUnicodeLocaleAttribute(attribute);
2707             } catch (LocaleSyntaxException e) {
2708                 throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2709             }
2710             return this;
2711         }
2712 
2713         /**
2714          * Resets the builder to its initial, empty state.
2715          *
2716          * @return This builder.
2717          */
2718         public Builder clear() {
2719             localeBuilder.clear();
2720             return this;
2721         }
2722 
2723         /**
2724          * Resets the extensions to their initial, empty state.
2725          * Language, script, region and variant are unchanged.
2726          *
2727          * @return This builder.
2728          * @see #setExtension(char, String)
2729          */
2730         public Builder clearExtensions() {
2731             localeBuilder.clearExtensions();
2732             return this;
2733         }
2734 
2735         /**
2736          * Returns an instance of <code>Locale</code> created from the fields set
2737          * on this builder.
2738          *
2739          * <p>This applies the conversions listed in {@link Locale#forLanguageTag}
2740          * when constructing a Locale. (Grandfathered tags are handled in
2741          * {@link #setLanguageTag}.)
2742          *
2743          * @return A Locale.
2744          */
2745         public Locale build() {
2746             BaseLocale baseloc = localeBuilder.getBaseLocale();
2747             LocaleExtensions extensions = localeBuilder.getLocaleExtensions();
2748             if (extensions == null && baseloc.getVariant().length() > 0) {
2749                 extensions = getCompatibilityExtensions(baseloc.getLanguage(), baseloc.getScript(),
2750                         baseloc.getRegion(), baseloc.getVariant());
2751             }
2752             return Locale.getInstance(baseloc, extensions);
2753         }
2754     }
2755 
2756     /**
2757      * This enum provides constants to select a filtering mode for locale
2758      * matching. Refer to <a href="http://tools.ietf.org/html/rfc4647">RFC 4647
2759      * Matching of Language Tags</a> for details.
2760      *
2761      * <p>As an example, think of two Language Priority Lists each of which
2762      * includes only one language range and a set of following language tags:
2763      *
2764      * <pre>
2765      *    de (German)
2766      *    de-DE (German, Germany)
2767      *    de-Deva (German, in Devanagari script)
2768      *    de-Deva-DE (German, in Devanagari script, Germany)
2769      *    de-DE-1996 (German, Germany, orthography of 1996)
2770      *    de-Latn-DE (German, in Latin script, Germany)
2771      *    de-Latn-DE-1996 (German, in Latin script, Germany, orthography of 1996)
2772      * </pre>
2773      *
2774      * The filtering method will behave as follows:
2775      *
2776      * <table class="altrows">
2777      * <caption>Filtering method behavior</caption>
2778      * <thead>
2779      * <tr>
2780      * <th>Filtering Mode</th>
2781      * <th>Language Priority List: {@code "de-DE"}</th>
2782      * <th>Language Priority List: {@code "de-*-DE"}</th>
2783      * </tr>
2784      * </thead>
2785      * <tbody>
2786      * <tr>
2787      * <td style="vertical-align:top">
2788      * {@link FilteringMode#AUTOSELECT_FILTERING AUTOSELECT_FILTERING}
2789      * </td>
2790      * <td style="vertical-align:top">
2791      * Performs <em>basic</em> filtering and returns {@code "de-DE"} and
2792      * {@code "de-DE-1996"}.
2793      * </td>
2794      * <td style="vertical-align:top">
2795      * Performs <em>extended</em> filtering and returns {@code "de-DE"},
2796      * {@code "de-Deva-DE"}, {@code "de-DE-1996"}, {@code "de-Latn-DE"}, and
2797      * {@code "de-Latn-DE-1996"}.
2798      * </td>
2799      * </tr>
2800      * <tr>
2801      * <td style="vertical-align:top">
2802      * {@link FilteringMode#EXTENDED_FILTERING EXTENDED_FILTERING}
2803      * </td>
2804      * <td style="vertical-align:top">
2805      * Performs <em>extended</em> filtering and returns {@code "de-DE"},
2806      * {@code "de-Deva-DE"}, {@code "de-DE-1996"}, {@code "de-Latn-DE"}, and
2807      * {@code "de-Latn-DE-1996"}.
2808      * </td>
2809      * <td style="vertical-align:top">Same as above.</td>
2810      * </tr>
2811      * <tr>
2812      * <td style="vertical-align:top">
2813      * {@link FilteringMode#IGNORE_EXTENDED_RANGES IGNORE_EXTENDED_RANGES}
2814      * </td>
2815      * <td style="vertical-align:top">
2816      * Performs <em>basic</em> filtering and returns {@code "de-DE"} and
2817      * {@code "de-DE-1996"}.
2818      * </td>
2819      * <td style="vertical-align:top">
2820      * Performs <em>basic</em> filtering and returns {@code null} because
2821      * nothing matches.
2822      * </td>
2823      * </tr>
2824      * <tr>
2825      * <td style="vertical-align:top">
2826      * {@link FilteringMode#MAP_EXTENDED_RANGES MAP_EXTENDED_RANGES}
2827      * </td>
2828      * <td style="vertical-align:top">Same as above.</td>
2829      * <td style="vertical-align:top">
2830      * Performs <em>basic</em> filtering and returns {@code "de-DE"} and
2831      * {@code "de-DE-1996"} because {@code "de-*-DE"} is mapped to
2832      * {@code "de-DE"}.
2833      * </td>
2834      * </tr>
2835      * <tr>
2836      * <td style="vertical-align:top">
2837      * {@link FilteringMode#REJECT_EXTENDED_RANGES REJECT_EXTENDED_RANGES}
2838      * </td>
2839      * <td style="vertical-align:top">Same as above.</td>
2840      * <td style="vertical-align:top">
2841      * Throws {@link IllegalArgumentException} because {@code "de-*-DE"} is
2842      * not a valid basic language range.
2843      * </td>
2844      * </tr>
2845      * </tbody>
2846      * </table>
2847      *
2848      * @see #filter(List, Collection, FilteringMode)
2849      * @see #filterTags(List, Collection, FilteringMode)
2850      *
2851      * @since 1.8
2852      */
2853     public static enum FilteringMode {
2854         /**
2855          * Specifies automatic filtering mode based on the given Language
2856          * Priority List consisting of language ranges. If all of the ranges
2857          * are basic, basic filtering is selected. Otherwise, extended
2858          * filtering is selected.
2859          */
2860         AUTOSELECT_FILTERING,
2861 
2862         /**
2863          * Specifies extended filtering.
2864          */
2865         EXTENDED_FILTERING,
2866 
2867         /**
2868          * Specifies basic filtering: Note that any extended language ranges
2869          * included in the given Language Priority List are ignored.
2870          */
2871         IGNORE_EXTENDED_RANGES,
2872 
2873         /**
2874          * Specifies basic filtering: If any extended language ranges are
2875          * included in the given Language Priority List, they are mapped to the
2876          * basic language range. Specifically, a language range starting with a
2877          * subtag {@code "*"} is treated as a language range {@code "*"}. For
2878          * example, {@code "*-US"} is treated as {@code "*"}. If {@code "*"} is
2879          * not the first subtag, {@code "*"} and extra {@code "-"} are removed.
2880          * For example, {@code "ja-*-JP"} is mapped to {@code "ja-JP"}.
2881          */
2882         MAP_EXTENDED_RANGES,
2883 
2884         /**
2885          * Specifies basic filtering: If any extended language ranges are
2886          * included in the given Language Priority List, the list is rejected
2887          * and the filtering method throws {@link IllegalArgumentException}.
2888          */
2889         REJECT_EXTENDED_RANGES
2890     };
2891 
2892     /**
2893      * This class expresses a <em>Language Range</em> defined in
2894      * <a href="http://tools.ietf.org/html/rfc4647">RFC 4647 Matching of
2895      * Language Tags</a>. A language range is an identifier which is used to
2896      * select language tag(s) meeting specific requirements by using the
2897      * mechanisms described in <a href="Locale.html#LocaleMatching">Locale
2898      * Matching</a>. A list which represents a user's preferences and consists
2899      * of language ranges is called a <em>Language Priority List</em>.
2900      *
2901      * <p>There are two types of language ranges: basic and extended. In RFC
2902      * 4647, the syntax of language ranges is expressed in
2903      * <a href="http://tools.ietf.org/html/rfc4234">ABNF</a> as follows:
2904      * <blockquote>
2905      * <pre>
2906      *     basic-language-range    = (1*8ALPHA *("-" 1*8alphanum)) / "*"
2907      *     extended-language-range = (1*8ALPHA / "*")
2908      *                               *("-" (1*8alphanum / "*"))
2909      *     alphanum                = ALPHA / DIGIT
2910      * </pre>
2911      * </blockquote>
2912      * For example, {@code "en"} (English), {@code "ja-JP"} (Japanese, Japan),
2913      * {@code "*"} (special language range which matches any language tag) are
2914      * basic language ranges, whereas {@code "*-CH"} (any languages,
2915      * Switzerland), {@code "es-*"} (Spanish, any regions), and
2916      * {@code "zh-Hant-*"} (Traditional Chinese, any regions) are extended
2917      * language ranges.
2918      *
2919      * @see #filter
2920      * @see #filterTags
2921      * @see #lookup
2922      * @see #lookupTag
2923      *
2924      * @since 1.8
2925      */
2926     public static final class LanguageRange {
2927 
2928        /**
2929         * A constant holding the maximum value of weight, 1.0, which indicates
2930         * that the language range is a good fit for the user.
2931         */
2932         public static final double MAX_WEIGHT = 1.0;
2933 
2934        /**
2935         * A constant holding the minimum value of weight, 0.0, which indicates
2936         * that the language range is not a good fit for the user.
2937         */
2938         public static final double MIN_WEIGHT = 0.0;
2939 
2940         private final String range;
2941         private final double weight;
2942 
2943         private volatile int hash;
2944 
2945         /**
2946          * Constructs a {@code LanguageRange} using the given {@code range}.
2947          * Note that no validation is done against the IANA Language Subtag
2948          * Registry at time of construction.
2949          *
2950          * <p>This is equivalent to {@code LanguageRange(range, MAX_WEIGHT)}.
2951          *
2952          * @param range a language range
2953          * @throws NullPointerException if the given {@code range} is
2954          *     {@code null}
2955          * @throws IllegalArgumentException if the given {@code range} does not
2956          * comply with the syntax of the language range mentioned in RFC 4647
2957          */
2958         public LanguageRange(String range) {
2959             this(range, MAX_WEIGHT);
2960         }
2961 
2962         /**
2963          * Constructs a {@code LanguageRange} using the given {@code range} and
2964          * {@code weight}. Note that no validation is done against the IANA
2965          * Language Subtag Registry at time of construction.
2966          *
2967          * @param range  a language range
2968          * @param weight a weight value between {@code MIN_WEIGHT} and
2969          *     {@code MAX_WEIGHT}
2970          * @throws NullPointerException if the given {@code range} is
2971          *     {@code null}
2972          * @throws IllegalArgumentException if the given {@code range} does not
2973          * comply with the syntax of the language range mentioned in RFC 4647
2974          * or if the given {@code weight} is less than {@code MIN_WEIGHT}
2975          * or greater than {@code MAX_WEIGHT}
2976          */
2977         public LanguageRange(String range, double weight) {
2978             if (range == null) {
2979                 throw new NullPointerException();
2980             }
2981             if (weight < MIN_WEIGHT || weight > MAX_WEIGHT) {
2982                 throw new IllegalArgumentException("weight=" + weight);
2983             }
2984 
2985             range = range.toLowerCase(Locale.ROOT);
2986 
2987             // Do syntax check.
2988             boolean isIllFormed = false;
2989             String[] subtags = range.split("-");
2990             if (isSubtagIllFormed(subtags[0], true)
2991                 || range.endsWith("-")) {
2992                 isIllFormed = true;
2993             } else {
2994                 for (int i = 1; i < subtags.length; i++) {
2995                     if (isSubtagIllFormed(subtags[i], false)) {
2996                         isIllFormed = true;
2997                         break;
2998                     }
2999                 }
3000             }
3001             if (isIllFormed) {
3002                 throw new IllegalArgumentException("range=" + range);
3003             }
3004 
3005             this.range = range;
3006             this.weight = weight;
3007         }
3008 
3009         private static boolean isSubtagIllFormed(String subtag,
3010                                                  boolean isFirstSubtag) {
3011             if (subtag.equals("") || subtag.length() > 8) {
3012                 return true;
3013             } else if (subtag.equals("*")) {
3014                 return false;
3015             }
3016             char[] charArray = subtag.toCharArray();
3017             if (isFirstSubtag) { // ALPHA
3018                 for (char c : charArray) {
3019                     if (c < 'a' || c > 'z') {
3020                         return true;
3021                     }
3022                 }
3023             } else { // ALPHA / DIGIT
3024                 for (char c : charArray) {
3025                     if (c < '0' || (c > '9' && c < 'a') || c > 'z') {
3026                         return true;
3027                     }
3028                 }
3029             }
3030             return false;
3031         }
3032 
3033         /**
3034          * Returns the language range of this {@code LanguageRange}.
3035          *
3036          * @return the language range.
3037          */
3038         public String getRange() {
3039             return range;
3040         }
3041 
3042         /**
3043          * Returns the weight of this {@code LanguageRange}.
3044          *
3045          * @return the weight value.
3046          */
3047         public double getWeight() {
3048             return weight;
3049         }
3050 
3051         /**
3052          * Parses the given {@code ranges} to generate a Language Priority List.
3053          *
3054          * <p>This method performs a syntactic check for each language range in
3055          * the given {@code ranges} but doesn't do validation using the IANA
3056          * Language Subtag Registry.
3057          *
3058          * <p>The {@code ranges} to be given can take one of the following
3059          * forms:
3060          *
3061          * <pre>
3062          *   "Accept-Language: ja,en;q=0.4"  (weighted list with Accept-Language prefix)
3063          *   "ja,en;q=0.4"                   (weighted list)
3064          *   "ja,en"                         (prioritized list)
3065          * </pre>
3066          *
3067          * In a weighted list, each language range is given a weight value.
3068          * The weight value is identical to the "quality value" in
3069          * <a href="http://tools.ietf.org/html/rfc2616">RFC 2616</a>, and it
3070          * expresses how much the user prefers  the language. A weight value is
3071          * specified after a corresponding language range followed by
3072          * {@code ";q="}, and the default weight value is {@code MAX_WEIGHT}
3073          * when it is omitted.
3074          *
3075          * <p>Unlike a weighted list, language ranges in a prioritized list
3076          * are sorted in the descending order based on its priority. The first
3077          * language range has the highest priority and meets the user's
3078          * preference most.
3079          *
3080          * <p>In either case, language ranges are sorted in descending order in
3081          * the Language Priority List based on priority or weight. If a
3082          * language range appears in the given {@code ranges} more than once,
3083          * only the first one is included on the Language Priority List.
3084          *
3085          * <p>The returned list consists of language ranges from the given
3086          * {@code ranges} and their equivalents found in the IANA Language
3087          * Subtag Registry. For example, if the given {@code ranges} is
3088          * {@code "Accept-Language: iw,en-us;q=0.7,en;q=0.3"}, the elements in
3089          * the list to be returned are:
3090          *
3091          * <pre>
3092          *  <b>Range</b>                                   <b>Weight</b>
3093          *    "iw" (older tag for Hebrew)             1.0
3094          *    "he" (new preferred code for Hebrew)    1.0
3095          *    "en-us" (English, United States)        0.7
3096          *    "en" (English)                          0.3
3097          * </pre>
3098          *
3099          * Two language ranges, {@code "iw"} and {@code "he"}, have the same
3100          * highest priority in the list. By adding {@code "he"} to the user's
3101          * Language Priority List, locale-matching method can find Hebrew as a
3102          * matching locale (or language tag) even if the application or system
3103          * offers only {@code "he"} as a supported locale (or language tag).
3104          *
3105          * @param ranges a list of comma-separated language ranges or a list of
3106          *     language ranges in the form of the "Accept-Language" header
3107          *     defined in <a href="http://tools.ietf.org/html/rfc2616">RFC
3108          *     2616</a>
3109          * @return a Language Priority List consisting of language ranges
3110          *     included in the given {@code ranges} and their equivalent
3111          *     language ranges if available. The list is modifiable.
3112          * @throws NullPointerException if {@code ranges} is null
3113          * @throws IllegalArgumentException if a language range or a weight
3114          *     found in the given {@code ranges} is ill-formed
3115          */
3116         public static List<LanguageRange> parse(String ranges) {
3117             return LocaleMatcher.parse(ranges);
3118         }
3119 
3120         /**
3121          * Parses the given {@code ranges} to generate a Language Priority
3122          * List, and then customizes the list using the given {@code map}.
3123          * This method is equivalent to
3124          * {@code mapEquivalents(parse(ranges), map)}.
3125          *
3126          * @param ranges a list of comma-separated language ranges or a list
3127          *     of language ranges in the form of the "Accept-Language" header
3128          *     defined in <a href="http://tools.ietf.org/html/rfc2616">RFC
3129          *     2616</a>
3130          * @param map a map containing information to customize language ranges
3131          * @return a Language Priority List with customization. The list is
3132          *     modifiable.
3133          * @throws NullPointerException if {@code ranges} is null
3134          * @throws IllegalArgumentException if a language range or a weight
3135          *     found in the given {@code ranges} is ill-formed
3136          * @see #parse(String)
3137          * @see #mapEquivalents
3138          */
3139         public static List<LanguageRange> parse(String ranges,
3140                                                 Map<String, List<String>> map) {
3141             return mapEquivalents(parse(ranges), map);
3142         }
3143 
3144         /**
3145          * Generates a new customized Language Priority List using the given
3146          * {@code priorityList} and {@code map}. If the given {@code map} is
3147          * empty, this method returns a copy of the given {@code priorityList}.
3148          *
3149          * <p>In the map, a key represents a language range whereas a value is
3150          * a list of equivalents of it. {@code '*'} cannot be used in the map.
3151          * Each equivalent language range has the same weight value as its
3152          * original language range.
3153          *
3154          * <pre>
3155          *  An example of map:
3156          *    <b>Key</b>                            <b>Value</b>
3157          *      "zh" (Chinese)                 "zh",
3158          *                                     "zh-Hans"(Simplified Chinese)
3159          *      "zh-HK" (Chinese, Hong Kong)   "zh-HK"
3160          *      "zh-TW" (Chinese, Taiwan)      "zh-TW"
3161          * </pre>
3162          *
3163          * The customization is performed after modification using the IANA
3164          * Language Subtag Registry.
3165          *
3166          * <p>For example, if a user's Language Priority List consists of five
3167          * language ranges ({@code "zh"}, {@code "zh-CN"}, {@code "en"},
3168          * {@code "zh-TW"}, and {@code "zh-HK"}), the newly generated Language
3169          * Priority List which is customized using the above map example will
3170          * consists of {@code "zh"}, {@code "zh-Hans"}, {@code "zh-CN"},
3171          * {@code "zh-Hans-CN"}, {@code "en"}, {@code "zh-TW"}, and
3172          * {@code "zh-HK"}.
3173          *
3174          * <p>{@code "zh-HK"} and {@code "zh-TW"} aren't converted to
3175          * {@code "zh-Hans-HK"} nor {@code "zh-Hans-TW"} even if they are
3176          * included in the Language Priority List. In this example, mapping
3177          * is used to clearly distinguish Simplified Chinese and Traditional
3178          * Chinese.
3179          *
3180          * <p>If the {@code "zh"}-to-{@code "zh"} mapping isn't included in the
3181          * map, a simple replacement will be performed and the customized list
3182          * won't include {@code "zh"} and {@code "zh-CN"}.
3183          *
3184          * @param priorityList user's Language Priority List
3185          * @param map a map containing information to customize language ranges
3186          * @return a new Language Priority List with customization. The list is
3187          *     modifiable.
3188          * @throws NullPointerException if {@code priorityList} is {@code null}
3189          * @see #parse(String, Map)
3190          */
3191         public static List<LanguageRange> mapEquivalents(
3192                                               List<LanguageRange>priorityList,
3193                                               Map<String, List<String>> map) {
3194             return LocaleMatcher.mapEquivalents(priorityList, map);
3195         }
3196 
3197         /**
3198          * Returns a hash code value for the object.
3199          *
3200          * @return  a hash code value for this object.
3201          */
3202         @Override
3203         public int hashCode() {
3204             int h = hash;
3205             if (h == 0) {
3206                 h = 17;
3207                 h = 37*h + range.hashCode();
3208                 long bitsWeight = Double.doubleToLongBits(weight);
3209                 h = 37*h + (int)(bitsWeight ^ (bitsWeight >>> 32));
3210                 if (h != 0) {
3211                     hash = h;
3212                 }
3213             }
3214             return h;
3215         }
3216 
3217         /**
3218          * Compares this object to the specified object. The result is true if
3219          * and only if the argument is not {@code null} and is a
3220          * {@code LanguageRange} object that contains the same {@code range}
3221          * and {@code weight} values as this object.
3222          *
3223          * @param obj the object to compare with
3224          * @return  {@code true} if this object's {@code range} and
3225          *     {@code weight} are the same as the {@code obj}'s; {@code false}
3226          *     otherwise.
3227          */
3228         @Override
3229         public boolean equals(Object obj) {
3230             if (this == obj) {
3231                 return true;
3232             }
3233             if (!(obj instanceof LanguageRange)) {
3234                 return false;
3235             }
3236             LanguageRange other = (LanguageRange)obj;
3237             return hash == other.hash
3238                    && range.equals(other.range)
3239                    && weight == other.weight;
3240         }
3241 
3242         /**
3243          * Returns an informative string representation of this {@code LanguageRange}
3244          * object, consisting of language range and weight if the range is
3245          * weighted and the weight is less than the max weight.
3246          *
3247          * @return a string representation of this {@code LanguageRange} object.
3248          */
3249         @Override
3250         public String toString() {
3251             return (weight == MAX_WEIGHT) ? range : range + ";q=" + weight;
3252         }
3253     }
3254 
3255     /**
3256      * Returns a list of matching {@code Locale} instances using the filtering
3257      * mechanism defined in RFC 4647.
3258      *
3259      * @param priorityList user's Language Priority List in which each language
3260      *     tag is sorted in descending order based on priority or weight
3261      * @param locales {@code Locale} instances used for matching
3262      * @param mode filtering mode
3263      * @return a list of {@code Locale} instances for matching language tags
3264      *     sorted in descending order based on priority or weight, or an empty
3265      *     list if nothing matches. The list is modifiable.
3266      * @throws NullPointerException if {@code priorityList} or {@code locales}
3267      *     is {@code null}
3268      * @throws IllegalArgumentException if one or more extended language ranges
3269      *     are included in the given list when
3270      *     {@link FilteringMode#REJECT_EXTENDED_RANGES} is specified
3271      *
3272      * @since 1.8
3273      */
3274     public static List<Locale> filter(List<LanguageRange> priorityList,
3275                                       Collection<Locale> locales,
3276                                       FilteringMode mode) {
3277         return LocaleMatcher.filter(priorityList, locales, mode);
3278     }
3279 
3280     /**
3281      * Returns a list of matching {@code Locale} instances using the filtering
3282      * mechanism defined in RFC 4647. This is equivalent to
3283      * {@link #filter(List, Collection, FilteringMode)} when {@code mode} is
3284      * {@link FilteringMode#AUTOSELECT_FILTERING}.
3285      *
3286      * @param priorityList user's Language Priority List in which each language
3287      *     tag is sorted in descending order based on priority or weight
3288      * @param locales {@code Locale} instances used for matching
3289      * @return a list of {@code Locale} instances for matching language tags
3290      *     sorted in descending order based on priority or weight, or an empty
3291      *     list if nothing matches. The list is modifiable.
3292      * @throws NullPointerException if {@code priorityList} or {@code locales}
3293      *     is {@code null}
3294      *
3295      * @since 1.8
3296      */
3297     public static List<Locale> filter(List<LanguageRange> priorityList,
3298                                       Collection<Locale> locales) {
3299         return filter(priorityList, locales, FilteringMode.AUTOSELECT_FILTERING);
3300     }
3301 
3302     /**
3303      * Returns a list of matching languages tags using the basic filtering
3304      * mechanism defined in RFC 4647.
3305      *
3306      * @param priorityList user's Language Priority List in which each language
3307      *     tag is sorted in descending order based on priority or weight
3308      * @param tags language tags
3309      * @param mode filtering mode
3310      * @return a list of matching language tags sorted in descending order
3311      *     based on priority or weight, or an empty list if nothing matches.
3312      *     The list is modifiable.
3313      * @throws NullPointerException if {@code priorityList} or {@code tags} is
3314      *     {@code null}
3315      * @throws IllegalArgumentException if one or more extended language ranges
3316      *     are included in the given list when
3317      *     {@link FilteringMode#REJECT_EXTENDED_RANGES} is specified
3318      *
3319      * @since 1.8
3320      */
3321     public static List<String> filterTags(List<LanguageRange> priorityList,
3322                                           Collection<String> tags,
3323                                           FilteringMode mode) {
3324         return LocaleMatcher.filterTags(priorityList, tags, mode);
3325     }
3326 
3327     /**
3328      * Returns a list of matching languages tags using the basic filtering
3329      * mechanism defined in RFC 4647. This is equivalent to
3330      * {@link #filterTags(List, Collection, FilteringMode)} when {@code mode}
3331      * is {@link FilteringMode#AUTOSELECT_FILTERING}.
3332      *
3333      * @param priorityList user's Language Priority List in which each language
3334      *     tag is sorted in descending order based on priority or weight
3335      * @param tags language tags
3336      * @return a list of matching language tags sorted in descending order
3337      *     based on priority or weight, or an empty list if nothing matches.
3338      *     The list is modifiable.
3339      * @throws NullPointerException if {@code priorityList} or {@code tags} is
3340      *     {@code null}
3341      *
3342      * @since 1.8
3343      */
3344     public static List<String> filterTags(List<LanguageRange> priorityList,
3345                                           Collection<String> tags) {
3346         return filterTags(priorityList, tags, FilteringMode.AUTOSELECT_FILTERING);
3347     }
3348 
3349     /**
3350      * Returns a {@code Locale} instance for the best-matching language
3351      * tag using the lookup mechanism defined in RFC 4647.
3352      *
3353      * @param priorityList user's Language Priority List in which each language
3354      *     tag is sorted in descending order based on priority or weight
3355      * @param locales {@code Locale} instances used for matching
3356      * @return the best matching <code>Locale</code> instance chosen based on
3357      *     priority or weight, or {@code null} if nothing matches.
3358      * @throws NullPointerException if {@code priorityList} or {@code tags} is
3359      *     {@code null}
3360      *
3361      * @since 1.8
3362      */
3363     public static Locale lookup(List<LanguageRange> priorityList,
3364                                 Collection<Locale> locales) {
3365         return LocaleMatcher.lookup(priorityList, locales);
3366     }
3367 
3368     /**
3369      * Returns the best-matching language tag using the lookup mechanism
3370      * defined in RFC 4647.
3371      *
3372      * @param priorityList user's Language Priority List in which each language
3373      *     tag is sorted in descending order based on priority or weight
3374      * @param tags language tangs used for matching
3375      * @return the best matching language tag chosen based on priority or
3376      *     weight, or {@code null} if nothing matches.
3377      * @throws NullPointerException if {@code priorityList} or {@code tags} is
3378      *     {@code null}
3379      *
3380      * @since 1.8
3381      */
3382     public static String lookupTag(List<LanguageRange> priorityList,
3383                                    Collection<String> tags) {
3384         return LocaleMatcher.lookupTag(priorityList, tags);
3385     }
3386 
3387 }