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