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