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