Locale.java revision 5a65597bdfe80ca0a0940b0f5c429dece7328b38
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.  Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 */
26
27/*
28 * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
29 * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
30 *
31 * The original version of this source code and documentation
32 * is copyrighted and owned by Taligent, Inc., a wholly-owned
33 * subsidiary of IBM. These materials are provided under terms
34 * of a License Agreement between Taligent and Sun. This technology
35 * is protected by multiple US and International patents.
36 *
37 * This notice and attribution to Taligent may not be removed.
38 * Taligent is a registered trademark of Taligent, Inc.
39 *
40 */
41
42package java.util;
43
44import java.io.IOException;
45import java.io.ObjectInputStream;
46import java.io.ObjectOutputStream;
47import java.io.ObjectStreamField;
48import java.io.Serializable;
49import java.security.AccessController;
50import java.text.MessageFormat;
51import java.util.spi.LocaleNameProvider;
52import libcore.icu.ICU;
53
54import sun.security.action.GetPropertyAction;
55import sun.util.LocaleServiceProviderPool;
56import sun.util.locale.BaseLocale;
57import sun.util.locale.InternalLocaleBuilder;
58import sun.util.locale.LanguageTag;
59import sun.util.locale.LocaleExtensions;
60import sun.util.locale.LocaleObjectCache;
61import sun.util.locale.LocaleSyntaxException;
62import sun.util.locale.LocaleUtils;
63import sun.util.locale.ParseStatus;
64import sun.util.locale.UnicodeLocaleExtension;
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</code> class implements identifiers
76 * interchangeable with BCP 47 (IETF BCP 47, "Tags for Identifying
77 * Languages"), with support for the LDML (UTS#35, "Unicode Locale
78 * Data Markup Language") BCP 47-compatible extensions for locale data
79 * exchange.
80 *
81 * <p> A <code>Locale</code> object logically consists of the fields
82 * described below.
83 *
84 * <dl>
85 *   <dt><a name="def_language"/><b>language</b></dt>
86 *
87 *   <dd>ISO 639 alpha-2 or alpha-3 language code, or registered
88 *   language subtags up to 8 alpha letters (for future enhancements).
89 *   When a language has both an alpha-2 code and an alpha-3 code, the
90 *   alpha-2 code must be used.  You can find a full list of valid
91 *   language codes in the IANA Language Subtag Registry (search for
92 *   "Type: language").  The language field is case insensitive, but
93 *   <code>Locale</code> always canonicalizes to lower case.</dd><br>
94 *
95 *   <dd>Well-formed language values have the form
96 *   <code>[a-zA-Z]{2,8}</code>.  Note that this is not the the full
97 *   BCP47 language production, since it excludes extlang.  They are
98 *   not needed since modern three-letter language codes replace
99 *   them.</dd><br>
100 *
101 *   <dd>Example: "en" (English), "ja" (Japanese), "kok" (Konkani)</dd><br>
102 *
103 *   <dt><a name="def_script"/><b>script</b></dt>
104 *
105 *   <dd>ISO 15924 alpha-4 script code.  You can find a full list of
106 *   valid script codes in the IANA Language Subtag Registry (search
107 *   for "Type: script").  The script field is case insensitive, but
108 *   <code>Locale</code> always canonicalizes to title case (the first
109 *   letter is upper case and the rest of the letters are lower
110 *   case).</dd><br>
111 *
112 *   <dd>Well-formed script values have the form
113 *   <code>[a-zA-Z]{4}</code></dd><br>
114 *
115 *   <dd>Example: "Latn" (Latin), "Cyrl" (Cyrillic)</dd><br>
116 *
117 *   <dt><a name="def_region"/><b>country (region)</b></dt>
118 *
119 *   <dd>ISO 3166 alpha-2 country code or UN M.49 numeric-3 area code.
120 *   You can find a full list of valid country and region codes in the
121 *   IANA Language Subtag Registry (search for "Type: region").  The
122 *   country (region) field is case insensitive, but
123 *   <code>Locale</code> always canonicalizes to upper case.</dd><br>
124 *
125 *   <dd>Well-formed country/region values have
126 *   the form <code>[a-zA-Z]{2} | [0-9]{3}</code></dd><br>
127 *
128 *   <dd>Example: "US" (United States), "FR" (France), "029"
129 *   (Caribbean)</dd><br>
130 *
131 *   <dt><a name="def_variant"/><b>variant</b></dt>
132 *
133 *   <dd>Any arbitrary value used to indicate a variation of a
134 *   <code>Locale</code>.  Where there are two or more variant values
135 *   each indicating its own semantics, these values should be ordered
136 *   by importance, with most important first, separated by
137 *   underscore('_').  The variant field is case sensitive.</dd><br>
138 *
139 *   <dd>Note: IETF BCP 47 places syntactic restrictions on variant
140 *   subtags.  Also BCP 47 subtags are strictly used to indicate
141 *   additional variations that define a language or its dialects that
142 *   are not covered by any combinations of language, script and
143 *   region subtags.  You can find a full list of valid variant codes
144 *   in the IANA Language Subtag Registry (search for "Type: variant").
145 *
146 *   <p>However, the variant field in <code>Locale</code> has
147 *   historically been used for any kind of variation, not just
148 *   language variations.  For example, some supported variants
149 *   available in Java SE Runtime Environments indicate alternative
150 *   cultural behaviors such as calendar type or number script.  In
151 *   BCP 47 this kind of information, which does not identify the
152 *   language, is supported by extension subtags or private use
153 *   subtags.</dd><br>
154 *
155 *   <dd>Well-formed variant values have the form <code>SUBTAG
156 *   (('_'|'-') SUBTAG)*</code> where <code>SUBTAG =
157 *   [0-9][0-9a-zA-Z]{3} | [0-9a-zA-Z]{5,8}</code>. (Note: BCP 47 only
158 *   uses hyphen ('-') as a delimiter, this is more lenient).</dd><br>
159 *
160 *   <dd>Example: "polyton" (Polytonic Greek), "POSIX"</dd><br>
161 *
162 *   <dt><a name="def_extensions"/><b>extensions</b></dt>
163 *
164 *   <dd>A map from single character keys to string values, indicating
165 *   extensions apart from language identification.  The extensions in
166 *   <code>Locale</code> implement the semantics and syntax of BCP 47
167 *   extension subtags and private use subtags. The extensions are
168 *   case insensitive, but <code>Locale</code> canonicalizes all
169 *   extension keys and values to lower case. Note that extensions
170 *   cannot have empty values.</dd><br>
171 *
172 *   <dd>Well-formed keys are single characters from the set
173 *   <code>[0-9a-zA-Z]</code>.  Well-formed values have the form
174 *   <code>SUBTAG ('-' SUBTAG)*</code> where for the key 'x'
175 *   <code>SUBTAG = [0-9a-zA-Z]{1,8}</code> and for other keys
176 *   <code>SUBTAG = [0-9a-zA-Z]{2,8}</code> (that is, 'x' allows
177 *   single-character subtags).</dd><br>
178 *
179 *   <dd>Example: key="u"/value="ca-japanese" (Japanese Calendar),
180 *   key="x"/value="java-1-7"</dd>
181 * </dl>
182 *
183 * <b>Note:</b> Although BCP 47 requires field values to be registered
184 * in the IANA Language Subtag Registry, the <code>Locale</code> class
185 * does not provide any validation features.  The <code>Builder</code>
186 * only checks if an individual field satisfies the syntactic
187 * requirement (is well-formed), but does not validate the value
188 * itself.  See {@link Builder} for details.
189 *
190 * <h4><a name="def_locale_extension">Unicode locale/language extension</h4>
191 *
192 * <p>UTS#35, "Unicode Locale Data Markup Language" defines optional
193 * attributes and keywords to override or refine the default behavior
194 * associated with a locale.  A keyword is represented by a pair of
195 * key and type.  For example, "nu-thai" indicates that Thai local
196 * digits (value:"thai") should be used for formatting numbers
197 * (key:"nu").
198 *
199 * <p>The keywords are mapped to a BCP 47 extension value using the
200 * extension key 'u' ({@link #UNICODE_LOCALE_EXTENSION}).  The above
201 * example, "nu-thai", becomes the extension "u-nu-thai".code
202 *
203 * <p>Thus, when a <code>Locale</code> object contains Unicode locale
204 * attributes and keywords,
205 * <code>getExtension(UNICODE_LOCALE_EXTENSION)</code> will return a
206 * String representing this information, for example, "nu-thai".  The
207 * <code>Locale</code> class also provides {@link
208 * #getUnicodeLocaleAttributes}, {@link #getUnicodeLocaleKeys}, and
209 * {@link #getUnicodeLocaleType} which allow you to access Unicode
210 * locale attributes and key/type pairs directly.  When represented as
211 * a string, the Unicode Locale Extension lists attributes
212 * alphabetically, followed by key/type sequences with keys listed
213 * alphabetically (the order of subtags comprising a key's type is
214 * fixed when the type is defined)
215 *
216 * <p>A well-formed locale key has the form
217 * <code>[0-9a-zA-Z]{2}</code>.  A well-formed locale type has the
218 * form <code>"" | [0-9a-zA-Z]{3,8} ('-' [0-9a-zA-Z]{3,8})*</code> (it
219 * can be empty, or a series of subtags 3-8 alphanums in length).  A
220 * well-formed locale attribute has the form
221 * <code>[0-9a-zA-Z]{3,8}</code> (it is a single subtag with the same
222 * form as a locale type subtag).
223 *
224 * <p>The Unicode locale extension specifies optional behavior in
225 * locale-sensitive services.  Although the LDML specification defines
226 * various keys and values, actual locale-sensitive service
227 * implementations in a Java Runtime Environment might not support any
228 * particular Unicode locale attributes or key/type pairs.
229 *
230 * <h4>Creating a Locale</h4>
231 *
232 * <p>There are several different ways to create a <code>Locale</code>
233 * object.
234 *
235 * <h5>Builder</h5>
236 *
237 * <p>Using {@link Builder} you can construct a <code>Locale</code> object
238 * that conforms to BCP 47 syntax.
239 *
240 * <h5>Constructors</h5>
241 *
242 * <p>The <code>Locale</code> class provides three constructors:
243 * <blockquote>
244 * <pre>
245 *     {@link #Locale(String language)}
246 *     {@link #Locale(String language, String country)}
247 *     {@link #Locale(String language, String country, String variant)}
248 * </pre>
249 * </blockquote>
250 * These constructors allow you to create a <code>Locale</code> object
251 * with language, country and variant, but you cannot specify
252 * script or extensions.
253 *
254 * <h5>Factory Methods</h5>
255 *
256 * <p>The method {@link #forLanguageTag} creates a <code>Locale</code>
257 * object for a well-formed BCP 47 language tag.
258 *
259 * <h5>Locale Constants</h5>
260 *
261 * <p>The <code>Locale</code> class provides a number of convenient constants
262 * that you can use to create <code>Locale</code> objects for commonly used
263 * locales. For example, the following creates a <code>Locale</code> object
264 * for the United States:
265 * <blockquote>
266 * <pre>
267 *     Locale.US
268 * </pre>
269 * </blockquote>
270 *
271 * <h4>Use of Locale</h4>
272 *
273 * <p>Once you've created a <code>Locale</code> you can query it for information
274 * about itself. Use <code>getCountry</code> to get the country (or region)
275 * code and <code>getLanguage</code> to get the language code.
276 * You can use <code>getDisplayCountry</code> to get the
277 * name of the country suitable for displaying to the user. Similarly,
278 * you can use <code>getDisplayLanguage</code> to get the name of
279 * the language suitable for displaying to the user. Interestingly,
280 * the <code>getDisplayXXX</code> methods are themselves locale-sensitive
281 * and have two versions: one that uses the default locale and one
282 * that uses the locale specified as an argument.
283 *
284 * <p>The Java Platform provides a number of classes that perform locale-sensitive
285 * operations. For example, the <code>NumberFormat</code> class formats
286 * numbers, currency, and percentages in a locale-sensitive manner. Classes
287 * such as <code>NumberFormat</code> have several convenience methods
288 * for creating a default object of that type. For example, the
289 * <code>NumberFormat</code> class provides these three convenience methods
290 * for creating a default <code>NumberFormat</code> object:
291 * <blockquote>
292 * <pre>
293 *     NumberFormat.getInstance()
294 *     NumberFormat.getCurrencyInstance()
295 *     NumberFormat.getPercentInstance()
296 * </pre>
297 * </blockquote>
298 * Each of these methods has two variants; one with an explicit locale
299 * and one without; the latter uses the default locale:
300 * <blockquote>
301 * <pre>
302 *     NumberFormat.getInstance(myLocale)
303 *     NumberFormat.getCurrencyInstance(myLocale)
304 *     NumberFormat.getPercentInstance(myLocale)
305 * </pre>
306 * </blockquote>
307 * A <code>Locale</code> is the mechanism for identifying the kind of object
308 * (<code>NumberFormat</code>) that you would like to get. The locale is
309 * <STRONG>just</STRONG> a mechanism for identifying objects,
310 * <STRONG>not</STRONG> a container for the objects themselves.
311 *
312 * <h4>Compatibility</h4>
313 *
314 * <p>In order to maintain compatibility with existing usage, Locale's
315 * constructors retain their behavior prior to the Java Runtime
316 * Environment version 1.7.  The same is largely true for the
317 * <code>toString</code> method. Thus Locale objects can continue to
318 * be used as they were. In particular, clients who parse the output
319 * of toString into language, country, and variant fields can continue
320 * to do so (although this is strongly discouraged), although the
321 * variant field will have additional information in it if script or
322 * extensions are present.
323 *
324 * <p>In addition, BCP 47 imposes syntax restrictions that are not
325 * imposed by Locale's constructors. This means that conversions
326 * between some Locales and BCP 47 language tags cannot be made without
327 * losing information. Thus <code>toLanguageTag</code> cannot
328 * represent the state of locales whose language, country, or variant
329 * do not conform to BCP 47.
330 *
331 * <p>Because of these issues, it is recommended that clients migrate
332 * away from constructing non-conforming locales and use the
333 * <code>forLanguageTag</code> and <code>Locale.Builder</code> APIs instead.
334 * Clients desiring a string representation of the complete locale can
335 * then always rely on <code>toLanguageTag</code> for this purpose.
336 *
337 * <h5><a name="special_cases_constructor"/>Special cases</h5>
338 *
339 * <p>For compatibility reasons, two
340 * non-conforming locales are treated as special cases.  These are
341 * <b><tt>ja_JP_JP</tt></b> and <b><tt>th_TH_TH</tt></b>. These are ill-formed
342 * in BCP 47 since the variants are too short. To ease migration to BCP 47,
343 * these are treated specially during construction.  These two cases (and only
344 * these) cause a constructor to generate an extension, all other values behave
345 * exactly as they did prior to Java 7.
346 *
347 * <p>Java has used <tt>ja_JP_JP</tt> to represent Japanese as used in
348 * Japan together with the Japanese Imperial calendar. This is now
349 * representable using a Unicode locale extension, by specifying the
350 * Unicode locale key <tt>ca</tt> (for "calendar") and type
351 * <tt>japanese</tt>. When the Locale constructor is called with the
352 * arguments "ja", "JP", "JP", the extension "u-ca-japanese" is
353 * automatically added.
354 *
355 * <p>Java has used <tt>th_TH_TH</tt> to represent Thai as used in
356 * Thailand together with Thai digits. This is also now representable using
357 * a Unicode locale extension, by specifying the Unicode locale key
358 * <tt>nu</tt> (for "number") and value <tt>thai</tt>. When the Locale
359 * constructor is called with the arguments "th", "TH", "TH", the
360 * extension "u-nu-thai" is automatically added.
361 *
362 * <h5>Serialization</h5>
363 *
364 * <p>During serialization, writeObject writes all fields to the output
365 * stream, including extensions.
366 *
367 * <p>During deserialization, readResolve adds extensions as described
368 * in <a href="#special_cases_constructor">Special Cases</a>, only
369 * for the two cases th_TH_TH and ja_JP_JP.
370 *
371 * <h5>Legacy language codes</h5>
372 *
373 * <p>Locale's constructor has always converted three language codes to
374 * their earlier, obsoleted forms: <tt>he</tt> maps to <tt>iw</tt>,
375 * <tt>yi</tt> maps to <tt>ji</tt>, and <tt>id</tt> maps to
376 * <tt>in</tt>.  This continues to be the case, in order to not break
377 * backwards compatibility.
378 *
379 * <p>The APIs added in 1.7 map between the old and new language codes,
380 * maintaining the old codes internal to Locale (so that
381 * <code>getLanguage</code> and <code>toString</code> reflect the old
382 * code), but using the new codes in the BCP 47 language tag APIs (so
383 * that <code>toLanguageTag</code> reflects the new one). This
384 * preserves the equivalence between Locales no matter which code or
385 * API is used to construct them. Java's default resource bundle
386 * lookup mechanism also implements this mapping, so that resources
387 * can be named using either convention, see {@link ResourceBundle.Control}.
388 *
389 * <h5>Three-letter language/country(region) codes</h5>
390 *
391 * <p>The Locale constructors have always specified that the language
392 * and the country param be two characters in length, although in
393 * practice they have accepted any length.  The specification has now
394 * been relaxed to allow language codes of two to eight characters and
395 * country (region) codes of two to three characters, and in
396 * particular, three-letter language codes and three-digit region
397 * codes as specified in the IANA Language Subtag Registry.  For
398 * compatibility, the implementation still does not impose a length
399 * constraint.
400 *
401 * @see Builder
402 * @see ResourceBundle
403 * @see java.text.Format
404 * @see java.text.NumberFormat
405 * @see java.text.Collator
406 * @author Mark Davis
407 * @since 1.1
408 */
409public final class Locale implements Cloneable, Serializable {
410
411    static private final  Cache LOCALECACHE = new Cache();
412
413    /** Useful constant for language.
414     */
415    static public final Locale ENGLISH = createConstant("en", "");
416
417    /** Useful constant for language.
418     */
419    static public final Locale FRENCH = createConstant("fr", "");
420
421    /** Useful constant for language.
422     */
423    static public final Locale GERMAN = createConstant("de", "");
424
425    /** Useful constant for language.
426     */
427    static public final Locale ITALIAN = createConstant("it", "");
428
429    /** Useful constant for language.
430     */
431    static public final Locale JAPANESE = createConstant("ja", "");
432
433    /** Useful constant for language.
434     */
435    static public final Locale KOREAN = createConstant("ko", "");
436
437    /** Useful constant for language.
438     */
439    static public final Locale CHINESE = createConstant("zh", "");
440
441    /** Useful constant for language.
442     */
443    static public final Locale SIMPLIFIED_CHINESE = createConstant("zh", "CN");
444
445    /** Useful constant for language.
446     */
447    static public final Locale TRADITIONAL_CHINESE = createConstant("zh", "TW");
448
449    /** Useful constant for country.
450     */
451    static public final Locale FRANCE = createConstant("fr", "FR");
452
453    /** Useful constant for country.
454     */
455    static public final Locale GERMANY = createConstant("de", "DE");
456
457    /** Useful constant for country.
458     */
459    static public final Locale ITALY = createConstant("it", "IT");
460
461    /** Useful constant for country.
462     */
463    static public final Locale JAPAN = createConstant("ja", "JP");
464
465    /** Useful constant for country.
466     */
467    static public final Locale KOREA = createConstant("ko", "KR");
468
469    /** Useful constant for country.
470     */
471    static public final Locale CHINA = SIMPLIFIED_CHINESE;
472
473    /** Useful constant for country.
474     */
475    static public final Locale PRC = SIMPLIFIED_CHINESE;
476
477    /** Useful constant for country.
478     */
479    static public final Locale TAIWAN = TRADITIONAL_CHINESE;
480
481    /** Useful constant for country.
482     */
483    static public final Locale UK = createConstant("en", "GB");
484
485    /** Useful constant for country.
486     */
487    static public final Locale US = createConstant("en", "US");
488
489    /** Useful constant for country.
490     */
491    static public final Locale CANADA = createConstant("en", "CA");
492
493    /** Useful constant for country.
494     */
495    static public final Locale CANADA_FRENCH = createConstant("fr", "CA");
496
497    /**
498     * ISO 639-3 generic code for undetermined languages.
499     */
500    private static final String UNDETERMINED_LANGUAGE = "und";
501
502    /**
503     * Useful constant for the root locale.  The root locale is the locale whose
504     * language, country, and variant are empty ("") strings.  This is regarded
505     * as the base locale of all locales, and is used as the language/country
506     * neutral locale for the locale sensitive operations.
507     *
508     * @since 1.6
509     */
510    static public final Locale ROOT = createConstant("", "");
511
512    /**
513     * The key for the private use extension ('x').
514     *
515     * @see #getExtension(char)
516     * @see Builder#setExtension(char, String)
517     * @since 1.7
518     */
519    static public final char PRIVATE_USE_EXTENSION = 'x';
520
521    /**
522     * The key for Unicode locale extension ('u').
523     *
524     * @see #getExtension(char)
525     * @see Builder#setExtension(char, String)
526     * @since 1.7
527     */
528    static public final char UNICODE_LOCALE_EXTENSION = 'u';
529
530    /** serialization ID
531     */
532    static final long serialVersionUID = 9149081749638150636L;
533
534    /**
535     * Display types for retrieving localized names from the name providers.
536     */
537    private static final int DISPLAY_LANGUAGE = 0;
538    private static final int DISPLAY_COUNTRY  = 1;
539    private static final int DISPLAY_VARIANT  = 2;
540    private static final int DISPLAY_SCRIPT   = 3;
541
542    /**
543     * Private constructor used by getInstance method
544     */
545    private Locale(BaseLocale baseLocale, LocaleExtensions extensions) {
546        this.baseLocale = baseLocale;
547        this.localeExtensions = extensions;
548    }
549
550    /**
551     * Construct a locale from language, country and variant.
552     * This constructor normalizes the language value to lowercase and
553     * the country value to uppercase.
554     * <p>
555     * <b>Note:</b>
556     * <ul>
557     * <li>ISO 639 is not a stable standard; some of the language codes it defines
558     * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
559     * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
560     * API on Locale will return only the OLD codes.
561     * <li>For backward compatibility reasons, this constructor does not make
562     * any syntactic checks on the input.
563     * <li>The two cases ("ja", "JP", "JP") and ("th", "TH", "TH") are handled specially,
564     * see <a href="#special_cases_constructor">Special Cases</a> for more information.
565     * </ul>
566     *
567     * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
568     * up to 8 characters in length.  See the <code>Locale</code> class description about
569     * valid language values.
570     * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code.
571     * See the <code>Locale</code> class description about valid country values.
572     * @param variant Any arbitrary value used to indicate a variation of a <code>Locale</code>.
573     * See the <code>Locale</code> class description for the details.
574     * @exception NullPointerException thrown if any argument is null.
575     */
576    public Locale(String language, String country, String variant) {
577        if (language== null || country == null || variant == null) {
578            throw new NullPointerException();
579        }
580        baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), "", country, variant);
581        localeExtensions = getCompatibilityExtensions(language, "", country, variant);
582    }
583
584    /**
585     * Construct a locale from language and country.
586     * This constructor normalizes the language value to lowercase and
587     * the country value to uppercase.
588     * <p>
589     * <b>Note:</b>
590     * <ul>
591     * <li>ISO 639 is not a stable standard; some of the language codes it defines
592     * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
593     * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
594     * API on Locale will return only the OLD codes.
595     * <li>For backward compatibility reasons, this constructor does not make
596     * any syntactic checks on the input.
597     * </ul>
598     *
599     * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
600     * up to 8 characters in length.  See the <code>Locale</code> class description about
601     * valid language values.
602     * @param country An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code.
603     * See the <code>Locale</code> class description about valid country values.
604     * @exception NullPointerException thrown if either argument is null.
605     */
606    public Locale(String language, String country) {
607        this(language, country, "");
608    }
609
610    /**
611     * Construct a locale from a language code.
612     * This constructor normalizes the language value to lowercase.
613     * <p>
614     * <b>Note:</b>
615     * <ul>
616     * <li>ISO 639 is not a stable standard; some of the language codes it defines
617     * (specifically "iw", "ji", and "in") have changed.  This constructor accepts both the
618     * old codes ("iw", "ji", and "in") and the new codes ("he", "yi", and "id"), but all other
619     * API on Locale will return only the OLD codes.
620     * <li>For backward compatibility reasons, this constructor does not make
621     * any syntactic checks on the input.
622     * </ul>
623     *
624     * @param language An ISO 639 alpha-2 or alpha-3 language code, or a language subtag
625     * up to 8 characters in length.  See the <code>Locale</code> class description about
626     * valid language values.
627     * @exception NullPointerException thrown if argument is null.
628     * @since 1.4
629     */
630    public Locale(String language) {
631        this(language, "", "");
632    }
633
634    /**
635     * This method must be called only for creating the Locale.*
636     * constants due to making shortcuts.
637     */
638    private static Locale createConstant(String lang, String country) {
639        BaseLocale base = BaseLocale.createInstance(lang, country);
640        return getInstance(base, null);
641    }
642
643    /**
644     * Returns a <code>Locale</code> constructed from the given
645     * <code>language</code>, <code>country</code> and
646     * <code>variant</code>. If the same <code>Locale</code> instance
647     * is available in the cache, then that instance is
648     * returned. Otherwise, a new <code>Locale</code> instance is
649     * created and cached.
650     *
651     * @param language lowercase 2 to 8 language code.
652     * @param country uppercase two-letter ISO-3166 code and numric-3 UN M.49 area code.
653     * @param variant vendor and browser specific code. See class description.
654     * @return the <code>Locale</code> instance requested
655     * @exception NullPointerException if any argument is null.
656     */
657    static Locale getInstance(String language, String country, String variant) {
658        return getInstance(language, "", country, variant, null);
659    }
660
661    static Locale getInstance(String language, String script, String country,
662                                      String variant, LocaleExtensions extensions) {
663        if (language== null || script == null || country == null || variant == null) {
664            throw new NullPointerException();
665        }
666
667        if (extensions == null) {
668            extensions = getCompatibilityExtensions(language, script, country, variant);
669        }
670
671        BaseLocale baseloc = BaseLocale.getInstance(language, script, country, variant);
672        return getInstance(baseloc, extensions);
673    }
674
675    static Locale getInstance(BaseLocale baseloc, LocaleExtensions extensions) {
676        LocaleKey key = new LocaleKey(baseloc, extensions);
677        return LOCALECACHE.get(key);
678    }
679
680    private static class Cache extends LocaleObjectCache<LocaleKey, Locale> {
681        private Cache() {
682        }
683
684        @Override
685        protected Locale createObject(LocaleKey key) {
686            return new Locale(key.base, key.exts);
687        }
688    }
689
690    private static final class LocaleKey {
691        private final BaseLocale base;
692        private final LocaleExtensions exts;
693        private final int hash;
694
695        private LocaleKey(BaseLocale baseLocale, LocaleExtensions extensions) {
696            base = baseLocale;
697            exts = extensions;
698
699            // Calculate the hash value here because it's always used.
700            int h = base.hashCode();
701            if (exts != null) {
702                h ^= exts.hashCode();
703            }
704            hash = h;
705        }
706
707        @Override
708        public boolean equals(Object obj) {
709            if (this == obj) {
710                return true;
711            }
712            if (!(obj instanceof LocaleKey)) {
713                return false;
714            }
715            LocaleKey other = (LocaleKey)obj;
716            if (hash != other.hash || !base.equals(other.base)) {
717                return false;
718            }
719            if (exts == null) {
720                return other.exts == null;
721            }
722            return exts.equals(other.exts);
723        }
724
725        @Override
726        public int hashCode() {
727            return hash;
728        }
729    }
730
731    /**
732     * Gets the current value of the default locale for this instance
733     * of the Java Virtual Machine.
734     * <p>
735     * The Java Virtual Machine sets the default locale during startup
736     * based on the host environment. It is used by many locale-sensitive
737     * methods if no locale is explicitly specified.
738     * It can be changed using the
739     * {@link #setDefault(java.util.Locale) setDefault} method.
740     *
741     * @return the default locale for this instance of the Java Virtual Machine
742     */
743    public static Locale getDefault() {
744        // do not synchronize this method - see 4071298
745        // it's OK if more than one default locale happens to be created
746        if (defaultLocale == null) {
747            initDefault();
748        }
749        return defaultLocale;
750    }
751
752    /**
753     * Gets the current value of the default locale for the specified Category
754     * for this instance of the Java Virtual Machine.
755     * <p>
756     * The Java Virtual Machine sets the default locale during startup based
757     * on the host environment. It is used by many locale-sensitive methods
758     * if no locale is explicitly specified. It can be changed using the
759     * setDefault(Locale.Category, Locale) method.
760     *
761     * @param category - the specified category to get the default locale
762     * @throws NullPointerException - if category is null
763     * @return the default locale for the specified Category for this instance
764     *     of the Java Virtual Machine
765     * @see #setDefault(Locale.Category, Locale)
766     * @since 1.7
767     */
768    public static Locale getDefault(Locale.Category category) {
769        // do not synchronize this method - see 4071298
770        // it's OK if more than one default locale happens to be created
771        switch (category) {
772        case DISPLAY:
773            if (defaultDisplayLocale == null) {
774                initDefault(category);
775            }
776            return defaultDisplayLocale;
777        case FORMAT:
778            if (defaultFormatLocale == null) {
779                initDefault(category);
780            }
781            return defaultFormatLocale;
782        default:
783            assert false: "Unknown Category";
784        }
785        return getDefault();
786    }
787
788    private static void initDefault() {
789        String language, region, script, country, variant;
790        language = AccessController.doPrivileged(
791            new GetPropertyAction("user.language", "en"));
792        // for compatibility, check for old user.region property
793        region = AccessController.doPrivileged(
794            new GetPropertyAction("user.region"));
795        if (region != null) {
796            // region can be of form country, country_variant, or _variant
797            int i = region.indexOf('_');
798            if (i >= 0) {
799                country = region.substring(0, i);
800                variant = region.substring(i + 1);
801            } else {
802                country = region;
803                variant = "";
804            }
805            script = "";
806        } else {
807            script = AccessController.doPrivileged(
808                new GetPropertyAction("user.script", ""));
809            country = AccessController.doPrivileged(
810                new GetPropertyAction("user.country", ""));
811            variant = AccessController.doPrivileged(
812                new GetPropertyAction("user.variant", ""));
813        }
814        defaultLocale = getInstance(language, script, country, variant, null);
815    }
816
817    private static void initDefault(Locale.Category category) {
818        // make sure defaultLocale is initialized
819        if (defaultLocale == null) {
820            initDefault();
821        }
822
823        Locale defaultCategoryLocale = getInstance(
824            AccessController.doPrivileged(
825                new GetPropertyAction(category.languageKey, defaultLocale.getLanguage())),
826            AccessController.doPrivileged(
827                new GetPropertyAction(category.scriptKey, defaultLocale.getScript())),
828            AccessController.doPrivileged(
829                new GetPropertyAction(category.countryKey, defaultLocale.getCountry())),
830            AccessController.doPrivileged(
831                new GetPropertyAction(category.variantKey, defaultLocale.getVariant())),
832            null);
833
834        switch (category) {
835        case DISPLAY:
836            defaultDisplayLocale = defaultCategoryLocale;
837            break;
838        case FORMAT:
839            defaultFormatLocale = defaultCategoryLocale;
840            break;
841        }
842    }
843
844    /**
845     * Sets the default locale for this instance of the Java Virtual Machine.
846     * This does not affect the host locale.
847     * <p>
848     * If there is a security manager, its <code>checkPermission</code>
849     * method is called with a <code>PropertyPermission("user.language", "write")</code>
850     * permission before the default locale is changed.
851     * <p>
852     * The Java Virtual Machine sets the default locale during startup
853     * based on the host environment. It is used by many locale-sensitive
854     * methods if no locale is explicitly specified.
855     * <p>
856     * Since changing the default locale may affect many different areas
857     * of functionality, this method should only be used if the caller
858     * is prepared to reinitialize locale-sensitive code running
859     * within the same Java Virtual Machine.
860     * <p>
861     * By setting the default locale with this method, all of the default
862     * locales for each Category are also set to the specified default locale.
863     *
864     * @throws SecurityException
865     *        if a security manager exists and its
866     *        <code>checkPermission</code> method doesn't allow the operation.
867     * @throws NullPointerException if <code>newLocale</code> is null
868     * @param newLocale the new default locale
869     * @see SecurityManager#checkPermission
870     * @see java.util.PropertyPermission
871     */
872    public static synchronized void setDefault(Locale newLocale) {
873        setDefault(Category.DISPLAY, newLocale);
874        setDefault(Category.FORMAT, newLocale);
875        defaultLocale = newLocale;
876        ICU.setDefaultLocale(newLocale.toLanguageTag());
877    }
878
879    /**
880     * Sets the default locale for the specified Category for this instance
881     * of the Java Virtual Machine. This does not affect the host locale.
882     * <p>
883     * If there is a security manager, its checkPermission method is called
884     * with a PropertyPermission("user.language", "write") permission before
885     * the default locale is changed.
886     * <p>
887     * The Java Virtual Machine sets the default locale during startup based
888     * on the host environment. It is used by many locale-sensitive methods
889     * if no locale is explicitly specified.
890     * <p>
891     * Since changing the default locale may affect many different areas of
892     * functionality, this method should only be used if the caller is
893     * prepared to reinitialize locale-sensitive code running within the
894     * same Java Virtual Machine.
895     * <p>
896     *
897     * @param category - the specified category to set the default locale
898     * @param newLocale - the new default locale
899     * @throws SecurityException - if a security manager exists and its
900     *     checkPermission method doesn't allow the operation.
901     * @throws NullPointerException - if category and/or newLocale is null
902     * @see SecurityManager#checkPermission(java.security.Permission)
903     * @see PropertyPermission
904     * @see #getDefault(Locale.Category)
905     * @since 1.7
906     */
907    public static synchronized void setDefault(Locale.Category category,
908        Locale newLocale) {
909        if (category == null)
910            throw new NullPointerException("Category cannot be NULL");
911        if (newLocale == null)
912            throw new NullPointerException("Can't set default locale to NULL");
913
914        SecurityManager sm = System.getSecurityManager();
915        if (sm != null) sm.checkPermission(new PropertyPermission
916                        ("user.language", "write"));
917        switch (category) {
918        case DISPLAY:
919            defaultDisplayLocale = newLocale;
920            break;
921        case FORMAT:
922            defaultFormatLocale = newLocale;
923            break;
924        default:
925            assert false: "Unknown Category";
926        }
927    }
928
929    /**
930     * Returns an array of all installed locales.
931     * The returned array represents the union of locales supported
932     * by the Java runtime environment and by installed
933     * {@link java.util.spi.LocaleServiceProvider LocaleServiceProvider}
934     * implementations.  It must contain at least a <code>Locale</code>
935     * instance equal to {@link java.util.Locale#US Locale.US}.
936     *
937     * @return An array of installed locales.
938     */
939    public static Locale[] getAvailableLocales() {
940        return LocaleServiceProviderPool.getAllAvailableLocales();
941    }
942
943    /**
944     * Returns a list of all 2-letter country codes defined in ISO 3166.
945     * Can be used to create Locales.
946     * <p>
947     * <b>Note:</b> The <code>Locale</code> class also supports other codes for
948     * country (region), such as 3-letter numeric UN M.49 area codes.
949     * Therefore, the list returned by this method does not contain ALL valid
950     * codes that can be used to create Locales.
951     */
952    public static String[] getISOCountries() {
953        // Android-changed: Use ICU.
954        return ICU.getISOCountries();
955    }
956
957    /**
958     * Returns a list of all 2-letter language codes defined in ISO 639.
959     * Can be used to create Locales.
960     * <p>
961     * <b>Note:</b>
962     * <ul>
963     * <li>ISO 639 is not a stable standard&mdash; some languages' codes have changed.
964     * The list this function returns includes both the new and the old codes for the
965     * languages whose codes have changed.
966     * <li>The <code>Locale</code> class also supports language codes up to
967     * 8 characters in length.  Therefore, the list returned by this method does
968     * not contain ALL valid codes that can be used to create Locales.
969     * </ul>
970     */
971    public static String[] getISOLanguages() {
972        // Android-changed: Use ICU.
973        return ICU.getISOLanguages();
974    }
975
976    /**
977     * Returns the language code of this Locale.
978     *
979     * <p><b>Note:</b> ISO 639 is not a stable standard&mdash; some languages' codes have changed.
980     * Locale's constructor recognizes both the new and the old codes for the languages
981     * whose codes have changed, but this function always returns the old code.  If you
982     * want to check for a specific language whose code has changed, don't do
983     * <pre>
984     * if (locale.getLanguage().equals("he")) // BAD!
985     *    ...
986     * </pre>
987     * Instead, do
988     * <pre>
989     * if (locale.getLanguage().equals(new Locale("he").getLanguage()))
990     *    ...
991     * </pre>
992     * @return The language code, or the empty string if none is defined.
993     * @see #getDisplayLanguage
994     */
995    public String getLanguage() {
996        return baseLocale.getLanguage();
997    }
998
999    /**
1000     * Returns the script for this locale, which should
1001     * either be the empty string or an ISO 15924 4-letter script
1002     * code. The first letter is uppercase and the rest are
1003     * lowercase, for example, 'Latn', 'Cyrl'.
1004     *
1005     * @return The script code, or the empty string if none is defined.
1006     * @see #getDisplayScript
1007     * @since 1.7
1008     */
1009    public String getScript() {
1010        return baseLocale.getScript();
1011    }
1012
1013    /**
1014     * Returns the country/region code for this locale, which should
1015     * either be the empty string, an uppercase ISO 3166 2-letter code,
1016     * or a UN M.49 3-digit code.
1017     *
1018     * @return The country/region code, or the empty string if none is defined.
1019     * @see #getDisplayCountry
1020     */
1021    public String getCountry() {
1022        return baseLocale.getRegion();
1023    }
1024
1025    /**
1026     * Returns the variant code for this locale.
1027     *
1028     * @return The variant code, or the empty string if none is defined.
1029     * @see #getDisplayVariant
1030     */
1031    public String getVariant() {
1032        return baseLocale.getVariant();
1033    }
1034
1035    /**
1036     * Returns the extension (or private use) value associated with
1037     * the specified key, or null if there is no extension
1038     * associated with the key. To be well-formed, the key must be one
1039     * of <code>[0-9A-Za-z]</code>. Keys are case-insensitive, so
1040     * for example 'z' and 'Z' represent the same extension.
1041     *
1042     * @param key the extension key
1043     * @return The extension, or null if this locale defines no
1044     * extension for the specified key.
1045     * @throws IllegalArgumentException if key is not well-formed
1046     * @see #PRIVATE_USE_EXTENSION
1047     * @see #UNICODE_LOCALE_EXTENSION
1048     * @since 1.7
1049     */
1050    public String getExtension(char key) {
1051        if (!LocaleExtensions.isValidKey(key)) {
1052            throw new IllegalArgumentException("Ill-formed extension key: " + key);
1053        }
1054        return (localeExtensions == null) ? null : localeExtensions.getExtensionValue(key);
1055    }
1056
1057    /**
1058     * Returns the set of extension keys associated with this locale, or the
1059     * empty set if it has no extensions. The returned set is unmodifiable.
1060     * The keys will all be lower-case.
1061     *
1062     * @return The set of extension keys, or the empty set if this locale has
1063     * no extensions.
1064     * @since 1.7
1065     */
1066    public Set<Character> getExtensionKeys() {
1067        if (localeExtensions == null) {
1068            return Collections.emptySet();
1069        }
1070        return localeExtensions.getKeys();
1071    }
1072
1073    /**
1074     * Returns the set of unicode locale attributes associated with
1075     * this locale, or the empty set if it has no attributes. The
1076     * returned set is unmodifiable.
1077     *
1078     * @return The set of attributes.
1079     * @since 1.7
1080     */
1081    public Set<String> getUnicodeLocaleAttributes() {
1082        if (localeExtensions == null) {
1083            return Collections.emptySet();
1084        }
1085        return localeExtensions.getUnicodeLocaleAttributes();
1086    }
1087
1088    /**
1089     * Returns the Unicode locale type associated with the specified Unicode locale key
1090     * for this locale. Returns the empty string for keys that are defined with no type.
1091     * Returns null if the key is not defined. Keys are case-insensitive. The key must
1092     * be two alphanumeric characters ([0-9a-zA-Z]), or an IllegalArgumentException is
1093     * thrown.
1094     *
1095     * @param key the Unicode locale key
1096     * @return The Unicode locale type associated with the key, or null if the
1097     * locale does not define the key.
1098     * @throws IllegalArgumentException if the key is not well-formed
1099     * @throws NullPointerException if <code>key</code> is null
1100     * @since 1.7
1101     */
1102    public String getUnicodeLocaleType(String key) {
1103        if (!UnicodeLocaleExtension.isKey(key)) {
1104            throw new IllegalArgumentException("Ill-formed Unicode locale key: " + key);
1105        }
1106        return (localeExtensions == null) ? null : localeExtensions.getUnicodeLocaleType(key);
1107    }
1108
1109    /**
1110     * Returns the set of Unicode locale keys defined by this locale, or the empty set if
1111     * this locale has none.  The returned set is immutable.  Keys are all lower case.
1112     *
1113     * @return The set of Unicode locale keys, or the empty set if this locale has
1114     * no Unicode locale keywords.
1115     * @since 1.7
1116     */
1117    public Set<String> getUnicodeLocaleKeys() {
1118        if (localeExtensions == null) {
1119            return Collections.emptySet();
1120        }
1121        return localeExtensions.getUnicodeLocaleKeys();
1122    }
1123
1124    /**
1125     * Package locale method returning the Locale's BaseLocale,
1126     * used by ResourceBundle
1127     * @return base locale of this Locale
1128     */
1129    BaseLocale getBaseLocale() {
1130        return baseLocale;
1131    }
1132
1133    /**
1134     * Package private method returning the Locale's LocaleExtensions,
1135     * used by ResourceBundle.
1136     * @return locale exnteions of this Locale,
1137     *         or {@code null} if no extensions are defined
1138     */
1139     LocaleExtensions getLocaleExtensions() {
1140         return localeExtensions;
1141     }
1142
1143    /**
1144     * Returns a string representation of this <code>Locale</code>
1145     * object, consisting of language, country, variant, script,
1146     * and extensions as below:
1147     * <p><blockquote>
1148     * language + "_" + country + "_" + (variant + "_#" | "#") + script + "-" + extensions
1149     * </blockquote>
1150     *
1151     * Language is always lower case, country is always upper case, script is always title
1152     * case, and extensions are always lower case.  Extensions and private use subtags
1153     * will be in canonical order as explained in {@link #toLanguageTag}.
1154     *
1155     * <p>When the locale has neither script nor extensions, the result is the same as in
1156     * Java 6 and prior.
1157     *
1158     * <p>If both the language and country fields are missing, this function will return
1159     * the empty string, even if the variant, script, or extensions field is present (you
1160     * can't have a locale with just a variant, the variant must accompany a well-formed
1161     * language or country code).
1162     *
1163     * <p>If script or extensions are present and variant is missing, no underscore is
1164     * added before the "#".
1165     *
1166     * <p>This behavior is designed to support debugging and to be compatible with
1167     * previous uses of <code>toString</code> that expected language, country, and variant
1168     * fields only.  To represent a Locale as a String for interchange purposes, use
1169     * {@link #toLanguageTag}.
1170     *
1171     * <p>Examples: <ul><tt>
1172     * <li>en
1173     * <li>de_DE
1174     * <li>_GB
1175     * <li>en_US_WIN
1176     * <li>de__POSIX
1177     * <li>zh_CN_#Hans
1178     * <li>zh_TW_#Hant-x-java
1179     * <li>th_TH_TH_#u-nu-thai</tt></ul>
1180     *
1181     * @return A string representation of the Locale, for debugging.
1182     * @see #getDisplayName
1183     * @see #toLanguageTag
1184     */
1185    @Override
1186    public final String toString() {
1187        boolean l = (baseLocale.getLanguage().length() != 0);
1188        boolean s = (baseLocale.getScript().length() != 0);
1189        boolean r = (baseLocale.getRegion().length() != 0);
1190        boolean v = (baseLocale.getVariant().length() != 0);
1191        boolean e = (localeExtensions != null && localeExtensions.getID().length() != 0);
1192
1193        StringBuilder result = new StringBuilder(baseLocale.getLanguage());
1194        if (r || (l && (v || s || e))) {
1195            result.append('_')
1196                .append(baseLocale.getRegion()); // This may just append '_'
1197        }
1198        if (v && (l || r)) {
1199            result.append('_')
1200                .append(baseLocale.getVariant());
1201        }
1202
1203        if (s && (l || r)) {
1204            result.append("_#")
1205                .append(baseLocale.getScript());
1206        }
1207
1208        if (e && (l || r)) {
1209            result.append('_');
1210            if (!s) {
1211                result.append('#');
1212            }
1213            result.append(localeExtensions.getID());
1214        }
1215
1216        return result.toString();
1217    }
1218
1219    /**
1220     * Returns a well-formed IETF BCP 47 language tag representing
1221     * this locale.
1222     *
1223     * <p>If this <code>Locale</code> has a language, country, or
1224     * variant that does not satisfy the IETF BCP 47 language tag
1225     * syntax requirements, this method handles these fields as
1226     * described below:
1227     *
1228     * <p><b>Language:</b> If language is empty, or not <a
1229     * href="#def_language" >well-formed</a> (for example "a" or
1230     * "e2"), it will be emitted as "und" (Undetermined).
1231     *
1232     * <p><b>Country:</b> If country is not <a
1233     * href="#def_region">well-formed</a> (for example "12" or "USA"),
1234     * it will be omitted.
1235     *
1236     * <p><b>Variant:</b> If variant <b>is</b> <a
1237     * href="#def_variant">well-formed</a>, each sub-segment
1238     * (delimited by '-' or '_') is emitted as a subtag.  Otherwise:
1239     * <ul>
1240     *
1241     * <li>if all sub-segments match <code>[0-9a-zA-Z]{1,8}</code>
1242     * (for example "WIN" or "Oracle_JDK_Standard_Edition"), the first
1243     * ill-formed sub-segment and all following will be appended to
1244     * the private use subtag.  The first appended subtag will be
1245     * "lvariant", followed by the sub-segments in order, separated by
1246     * hyphen. For example, "x-lvariant-WIN",
1247     * "Oracle-x-lvariant-JDK-Standard-Edition".
1248     *
1249     * <li>if any sub-segment does not match
1250     * <code>[0-9a-zA-Z]{1,8}</code>, the variant will be truncated
1251     * and the problematic sub-segment and all following sub-segments
1252     * will be omitted.  If the remainder is non-empty, it will be
1253     * emitted as a private use subtag as above (even if the remainder
1254     * turns out to be well-formed).  For example,
1255     * "Solaris_isjustthecoolestthing" is emitted as
1256     * "x-lvariant-Solaris", not as "solaris".</li></ul>
1257     *
1258     * <p><b>Special Conversions:</b> Java supports some old locale
1259     * representations, including deprecated ISO language codes,
1260     * for compatibility. This method performs the following
1261     * conversions:
1262     * <ul>
1263     *
1264     * <li>Deprecated ISO language codes "iw", "ji", and "in" are
1265     * converted to "he", "yi", and "id", respectively.
1266     *
1267     * <li>A locale with language "no", country "NO", and variant
1268     * "NY", representing Norwegian Nynorsk (Norway), is converted
1269     * to a language tag "nn-NO".</li></ul>
1270     *
1271     * <p><b>Note:</b> Although the language tag created by this
1272     * method is well-formed (satisfies the syntax requirements
1273     * defined by the IETF BCP 47 specification), it is not
1274     * necessarily a valid BCP 47 language tag.  For example,
1275     * <pre>
1276     *   new Locale("xx", "YY").toLanguageTag();</pre>
1277     *
1278     * will return "xx-YY", but the language subtag "xx" and the
1279     * region subtag "YY" are invalid because they are not registered
1280     * in the IANA Language Subtag Registry.
1281     *
1282     * @return a BCP47 language tag representing the locale
1283     * @see #forLanguageTag(String)
1284     * @since 1.7
1285     */
1286    public String toLanguageTag() {
1287        LanguageTag tag = LanguageTag.parseLocale(baseLocale, localeExtensions);
1288        StringBuilder buf = new StringBuilder();
1289
1290        String subtag = tag.getLanguage();
1291        if (subtag.length() > 0) {
1292            buf.append(LanguageTag.canonicalizeLanguage(subtag));
1293        }
1294
1295        subtag = tag.getScript();
1296        if (subtag.length() > 0) {
1297            buf.append(LanguageTag.SEP);
1298            buf.append(LanguageTag.canonicalizeScript(subtag));
1299        }
1300
1301        subtag = tag.getRegion();
1302        if (subtag.length() > 0) {
1303            buf.append(LanguageTag.SEP);
1304            buf.append(LanguageTag.canonicalizeRegion(subtag));
1305        }
1306
1307        List<String>subtags = tag.getVariants();
1308        for (String s : subtags) {
1309            buf.append(LanguageTag.SEP);
1310            // preserve casing
1311            buf.append(s);
1312        }
1313
1314        subtags = tag.getExtensions();
1315        for (String s : subtags) {
1316            buf.append(LanguageTag.SEP);
1317            buf.append(LanguageTag.canonicalizeExtension(s));
1318        }
1319
1320        subtag = tag.getPrivateuse();
1321        if (subtag.length() > 0) {
1322            if (buf.length() > 0) {
1323                buf.append(LanguageTag.SEP);
1324            }
1325            buf.append(LanguageTag.PRIVATEUSE).append(LanguageTag.SEP);
1326            // preserve casing
1327            buf.append(subtag);
1328        }
1329
1330        return buf.toString();
1331    }
1332
1333    /**
1334     * Returns a locale for the specified IETF BCP 47 language tag string.
1335     *
1336     * <p>If the specified language tag contains any ill-formed subtags,
1337     * the first such subtag and all following subtags are ignored.  Compare
1338     * to {@link Locale.Builder#setLanguageTag} which throws an exception
1339     * in this case.
1340     *
1341     * <p>The following <b>conversions</b> are performed:<ul>
1342     *
1343     * <li>The language code "und" is mapped to language "".
1344     *
1345     * <li>The language codes "he", "yi", and "id" are mapped to "iw",
1346     * "ji", and "in" respectively. (This is the same canonicalization
1347     * that's done in Locale's constructors.)
1348     *
1349     * <li>The portion of a private use subtag prefixed by "lvariant",
1350     * if any, is removed and appended to the variant field in the
1351     * result locale (without case normalization).  If it is then
1352     * empty, the private use subtag is discarded:
1353     *
1354     * <pre>
1355     *     Locale loc;
1356     *     loc = Locale.forLanguageTag("en-US-x-lvariant-POSIX");
1357     *     loc.getVariant(); // returns "POSIX"
1358     *     loc.getExtension('x'); // returns null
1359     *
1360     *     loc = Locale.forLanguageTag("de-POSIX-x-URP-lvariant-Abc-Def");
1361     *     loc.getVariant(); // returns "POSIX_Abc_Def"
1362     *     loc.getExtension('x'); // returns "urp"
1363     * </pre>
1364     *
1365     * <li>When the languageTag argument contains an extlang subtag,
1366     * the first such subtag is used as the language, and the primary
1367     * language subtag and other extlang subtags are ignored:
1368     *
1369     * <pre>
1370     *     Locale.forLanguageTag("ar-aao").getLanguage(); // returns "aao"
1371     *     Locale.forLanguageTag("en-abc-def-us").toString(); // returns "abc_US"
1372     * </pre>
1373     *
1374     * <li>Case is normalized except for variant tags, which are left
1375     * unchanged.  Language is normalized to lower case, script to
1376     * title case, country to upper case, and extensions to lower
1377     * case.
1378     *
1379     * <li>If, after processing, the locale would exactly match either
1380     * ja_JP_JP or th_TH_TH with no extensions, the appropriate
1381     * extensions are added as though the constructor had been called:
1382     *
1383     * <pre>
1384     *    Locale.forLanguageTag("ja-JP-x-lvariant-JP").toLanguageTag();
1385     *    // returns "ja-JP-u-ca-japanese-x-lvariant-JP"
1386     *    Locale.forLanguageTag("th-TH-x-lvariant-TH").toLanguageTag();
1387     *    // returns "th-TH-u-nu-thai-x-lvariant-TH"
1388     * <pre></ul>
1389     *
1390     * <p>This implements the 'Language-Tag' production of BCP47, and
1391     * so supports grandfathered (regular and irregular) as well as
1392     * private use language tags.  Stand alone private use tags are
1393     * represented as empty language and extension 'x-whatever',
1394     * and grandfathered tags are converted to their canonical replacements
1395     * where they exist.
1396     *
1397     * <p>Grandfathered tags with canonical replacements are as follows:
1398     *
1399     * <table>
1400     * <tbody align="center">
1401     * <tr><th>grandfathered tag</th><th>&nbsp;</th><th>modern replacement</th></tr>
1402     * <tr><td>art-lojban</td><td>&nbsp;</td><td>jbo</td></tr>
1403     * <tr><td>i-ami</td><td>&nbsp;</td><td>ami</td></tr>
1404     * <tr><td>i-bnn</td><td>&nbsp;</td><td>bnn</td></tr>
1405     * <tr><td>i-hak</td><td>&nbsp;</td><td>hak</td></tr>
1406     * <tr><td>i-klingon</td><td>&nbsp;</td><td>tlh</td></tr>
1407     * <tr><td>i-lux</td><td>&nbsp;</td><td>lb</td></tr>
1408     * <tr><td>i-navajo</td><td>&nbsp;</td><td>nv</td></tr>
1409     * <tr><td>i-pwn</td><td>&nbsp;</td><td>pwn</td></tr>
1410     * <tr><td>i-tao</td><td>&nbsp;</td><td>tao</td></tr>
1411     * <tr><td>i-tay</td><td>&nbsp;</td><td>tay</td></tr>
1412     * <tr><td>i-tsu</td><td>&nbsp;</td><td>tsu</td></tr>
1413     * <tr><td>no-bok</td><td>&nbsp;</td><td>nb</td></tr>
1414     * <tr><td>no-nyn</td><td>&nbsp;</td><td>nn</td></tr>
1415     * <tr><td>sgn-BE-FR</td><td>&nbsp;</td><td>sfb</td></tr>
1416     * <tr><td>sgn-BE-NL</td><td>&nbsp;</td><td>vgt</td></tr>
1417     * <tr><td>sgn-CH-DE</td><td>&nbsp;</td><td>sgg</td></tr>
1418     * <tr><td>zh-guoyu</td><td>&nbsp;</td><td>cmn</td></tr>
1419     * <tr><td>zh-hakka</td><td>&nbsp;</td><td>hak</td></tr>
1420     * <tr><td>zh-min-nan</td><td>&nbsp;</td><td>nan</td></tr>
1421     * <tr><td>zh-xiang</td><td>&nbsp;</td><td>hsn</td></tr>
1422     * </tbody>
1423     * </table>
1424     *
1425     * <p>Grandfathered tags with no modern replacement will be
1426     * converted as follows:
1427     *
1428     * <table>
1429     * <tbody align="center">
1430     * <tr><th>grandfathered tag</th><th>&nbsp;</th><th>converts to</th></tr>
1431     * <tr><td>cel-gaulish</td><td>&nbsp;</td><td>xtg-x-cel-gaulish</td></tr>
1432     * <tr><td>en-GB-oed</td><td>&nbsp;</td><td>en-GB-x-oed</td></tr>
1433     * <tr><td>i-default</td><td>&nbsp;</td><td>en-x-i-default</td></tr>
1434     * <tr><td>i-enochian</td><td>&nbsp;</td><td>und-x-i-enochian</td></tr>
1435     * <tr><td>i-mingo</td><td>&nbsp;</td><td>see-x-i-mingo</td></tr>
1436     * <tr><td>zh-min</td><td>&nbsp;</td><td>nan-x-zh-min</td></tr>
1437     * </tbody>
1438     * </table>
1439     *
1440     * <p>For a list of all grandfathered tags, see the
1441     * IANA Language Subtag Registry (search for "Type: grandfathered").
1442     *
1443     * <p><b>Note</b>: there is no guarantee that <code>toLanguageTag</code>
1444     * and <code>forLanguageTag</code> will round-trip.
1445     *
1446     * @param languageTag the language tag
1447     * @return The locale that best represents the language tag.
1448     * @throws NullPointerException if <code>languageTag</code> is <code>null</code>
1449     * @see #toLanguageTag()
1450     * @see java.util.Locale.Builder#setLanguageTag(String)
1451     * @since 1.7
1452     */
1453    public static Locale forLanguageTag(String languageTag) {
1454        LanguageTag tag = LanguageTag.parse(languageTag, null);
1455        InternalLocaleBuilder bldr = new InternalLocaleBuilder();
1456        bldr.setLanguageTag(tag);
1457        BaseLocale base = bldr.getBaseLocale();
1458        LocaleExtensions exts = bldr.getLocaleExtensions();
1459        if (exts == null && base.getVariant().length() > 0) {
1460            exts = getCompatibilityExtensions(base.getLanguage(), base.getScript(),
1461                                              base.getRegion(), base.getVariant());
1462        }
1463        return getInstance(base, exts);
1464    }
1465
1466    /**
1467     * Returns a three-letter abbreviation of this locale's language.
1468     * If the language matches an ISO 639-1 two-letter code, the
1469     * corresponding ISO 639-2/T three-letter lowercase code is
1470     * returned.  The ISO 639-2 language codes can be found on-line,
1471     * see "Codes for the Representation of Names of Languages Part 2:
1472     * Alpha-3 Code".  If the locale specifies a three-letter
1473     * language, the language is returned as is.  If the locale does
1474     * not specify a language the empty string is returned.
1475     *
1476     * @return A three-letter abbreviation of this locale's language.
1477     * @exception MissingResourceException Throws MissingResourceException if
1478     * three-letter language abbreviation is not available for this locale.
1479     */
1480    public String getISO3Language() throws MissingResourceException {
1481        // Android-changed: Use ICU.getIso3Language. Also return "" for empty languages
1482        // for the sake of backwards compatibility.
1483        String lang = baseLocale.getLanguage();
1484        if (lang.length() == 3) {
1485            return lang;
1486        } else if (lang.isEmpty()) {
1487            return "";
1488        }
1489
1490        String language3 = ICU.getISO3Language(lang);
1491        if (language3.isEmpty()) {
1492            throw new MissingResourceException("Couldn't find 3-letter language code for "
1493                    + lang, "FormatData_" + toString(), "ShortLanguage");
1494        }
1495
1496        return language3;
1497    }
1498
1499    /**
1500     * Returns a three-letter abbreviation for this locale's country.
1501     * If the country matches an ISO 3166-1 alpha-2 code, the
1502     * corresponding ISO 3166-1 alpha-3 uppercase code is returned.
1503     * If the locale doesn't specify a country, this will be the empty
1504     * string.
1505     *
1506     * <p>The ISO 3166-1 codes can be found on-line.
1507     *
1508     * @return A three-letter abbreviation of this locale's country.
1509     * @exception MissingResourceException Throws MissingResourceException if the
1510     * three-letter country abbreviation is not available for this locale.
1511     */
1512    public String getISO3Country() throws MissingResourceException {
1513        // Android changed: Use.getIso3Country. Also return "" for missing regions.
1514        final String region = baseLocale.getRegion();
1515        // Note that this will return an UN.M49 region code
1516        if (region.length() == 3) {
1517            return baseLocale.getRegion();
1518        } else if (region.isEmpty()) {
1519            return "";
1520        }
1521
1522        // Prefix "en-" because ICU doesn't really care about what the language is.
1523        String country3 = ICU.getISO3Country("en-" + region);
1524        if (country3 == null) {
1525            throw new MissingResourceException("Couldn't find 3-letter country code for "
1526                    + baseLocale.getRegion(), "FormatData_" + toString(), "ShortCountry");
1527        }
1528        return country3;
1529    }
1530
1531    /**
1532     * Returns a name for the locale's language that is appropriate for display to the
1533     * user.
1534     * If possible, the name returned will be localized for the default locale.
1535     * For example, if the locale is fr_FR and the default locale
1536     * is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and
1537     * the default locale is fr_FR, getDisplayLanguage() will return "anglais".
1538     * If the name returned cannot be localized for the default locale,
1539     * (say, we don't have a Japanese name for Croatian),
1540     * this function falls back on the English name, and uses the ISO code as a last-resort
1541     * value.  If the locale doesn't specify a language, this function returns the empty string.
1542     */
1543    public final String getDisplayLanguage() {
1544        return getDisplayLanguage(getDefault(Category.DISPLAY));
1545    }
1546
1547    /**
1548     * Returns the name of this locale's language, localized to {@code locale}.
1549     * If the language name is unknown, the language code is returned.
1550     */
1551    public String getDisplayLanguage(Locale locale) {
1552        String languageCode = baseLocale.getLanguage();
1553        if (languageCode.isEmpty()) {
1554            return "";
1555        }
1556
1557        // Hacks for backward compatibility.
1558        //
1559        // Our language tag will contain "und" if the languageCode is invalid
1560        // or missing. ICU will then return "langue indéterminée" or the equivalent
1561        // display language for the indeterminate language code.
1562        //
1563        // Sigh... ugh... and what not.
1564        final String normalizedLanguage = normalizeAndValidateLanguage(
1565                languageCode, false /* strict */);
1566        if (UNDETERMINED_LANGUAGE.equals(normalizedLanguage)) {
1567            return languageCode;
1568        }
1569
1570        // TODO: We need a new hack or a complete fix for http://b/8049507 --- We would
1571        // cover the frameworks' tracks when they were using "tl" instead of "fil".
1572        String result = ICU.getDisplayLanguage(this, locale);
1573        if (result == null) { // TODO: do we need to do this, or does ICU do it for us?
1574            result = ICU.getDisplayLanguage(this, Locale.getDefault());
1575        }
1576        return result;
1577    }
1578
1579    private static String normalizeAndValidateLanguage(String language, boolean strict) {
1580        if (language == null || language.isEmpty()) {
1581            return "";
1582        }
1583
1584        final String lowercaseLanguage = language.toLowerCase(Locale.ROOT);
1585        if (!isValidBcp47Alpha(lowercaseLanguage, 2, 3)) {
1586            if (strict) {
1587                throw new IllformedLocaleException("Invalid language: " + language);
1588            } else {
1589                return UNDETERMINED_LANGUAGE;
1590            }
1591        }
1592
1593        return lowercaseLanguage;
1594    }
1595
1596    /*
1597     * Checks whether a given string is an ASCII alphanumeric string.
1598     */
1599    private static boolean isAsciiAlphaNum(String string) {
1600        for (int i = 0; i < string.length(); i++) {
1601            final char character = string.charAt(i);
1602            if (!(character >= 'a' && character <= 'z' ||
1603                    character >= 'A' && character <= 'Z' ||
1604                    character >= '0' && character <= '9')) {
1605                return false;
1606            }
1607        }
1608
1609        return true;
1610    }
1611
1612    /**
1613     * Returns a name for the the locale's script that is appropriate for display to
1614     * the user. If possible, the name will be localized for the default locale.  Returns
1615     * the empty string if this locale doesn't specify a script code.
1616     *
1617     * @return the display name of the script code for the current default locale
1618     * @since 1.7
1619     */
1620    public String getDisplayScript() {
1621        return getDisplayScript(getDefault());
1622    }
1623
1624    /**
1625     * Returns the name of this locale's script code, localized to {@link Locale}. If the
1626     * script code is unknown, the return value of this method is the same as that of
1627     * {@link #getScript()}.
1628     *
1629     * @since 1.7
1630     */
1631    public String getDisplayScript(Locale locale) {
1632        String scriptCode = baseLocale.getScript();
1633        if (scriptCode.isEmpty()) {
1634            return "";
1635        }
1636
1637        String result = ICU.getDisplayScript(this, locale);
1638        if (result == null) { // TODO: do we need to do this, or does ICU do it for us?
1639            result = ICU.getDisplayScript(this, Locale.getDefault());
1640        }
1641
1642        return result;
1643
1644    }
1645
1646    /**
1647     * Returns a name for the locale's country that is appropriate for display to the
1648     * user.
1649     * If possible, the name returned will be localized for the default locale.
1650     * For example, if the locale is fr_FR and the default locale
1651     * is en_US, getDisplayCountry() will return "France"; if the locale is en_US and
1652     * the default locale is fr_FR, getDisplayCountry() will return "Etats-Unis".
1653     * If the name returned cannot be localized for the default locale,
1654     * (say, we don't have a Japanese name for Croatia),
1655     * this function falls back on the English name, and uses the ISO code as a last-resort
1656     * value.  If the locale doesn't specify a country, this function returns the empty string.
1657     */
1658    public final String getDisplayCountry() {
1659        return getDisplayCountry(getDefault(Category.DISPLAY));
1660    }
1661    /**
1662     * Returns the name of this locale's country, localized to {@code locale}.
1663     * Returns the empty string if this locale does not correspond to a specific
1664     * country.
1665     */
1666    public String getDisplayCountry(Locale locale) {
1667        String countryCode = baseLocale.getRegion();
1668        if (countryCode.isEmpty()) {
1669            return "";
1670        }
1671
1672        final String normalizedRegion = normalizeAndValidateRegion(
1673                countryCode, false /* strict */);
1674        if (normalizedRegion.isEmpty()) {
1675            return countryCode;
1676        }
1677
1678        String result = ICU.getDisplayCountry(this, locale);
1679        if (result == null) { // TODO: do we need to do this, or does ICU do it for us?
1680            result = ICU.getDisplayCountry(this, Locale.getDefault());
1681        }
1682        return result;
1683    }
1684
1685    private static String normalizeAndValidateRegion(String region, boolean strict) {
1686        if (region == null || region.isEmpty()) {
1687            return "";
1688        }
1689
1690        final String uppercaseRegion = region.toUpperCase(Locale.ROOT);
1691        if (!isValidBcp47Alpha(uppercaseRegion, 2, 2) &&
1692                !isUnM49AreaCode(uppercaseRegion)) {
1693            if (strict) {
1694                throw new IllformedLocaleException("Invalid region: " + region);
1695            } else {
1696                return "";
1697            }
1698        }
1699
1700        return uppercaseRegion;
1701    }
1702
1703    private static boolean isValidBcp47Alpha(String string, int lowerBound, int upperBound) {
1704        final int length = string.length();
1705        if (length < lowerBound || length > upperBound) {
1706            return false;
1707        }
1708
1709        for (int i = 0; i < length; ++i) {
1710            final char character = string.charAt(i);
1711            if (!(character >= 'a' && character <= 'z' ||
1712                    character >= 'A' && character <= 'Z')) {
1713                return false;
1714            }
1715        }
1716
1717        return true;
1718    }
1719
1720    /**
1721     * A UN M.49 is a 3 digit numeric code.
1722     */
1723    private static boolean isUnM49AreaCode(String code) {
1724        if (code.length() != 3) {
1725            return false;
1726        }
1727
1728        for (int i = 0; i < 3; ++i) {
1729            final char character = code.charAt(i);
1730            if (!(character >= '0' && character <= '9')) {
1731                return false;
1732            }
1733        }
1734
1735        return true;
1736    }
1737
1738    /**
1739     * Returns a name for the locale's variant code that is appropriate for display to the
1740     * user.  If possible, the name will be localized for the default locale.  If the locale
1741     * doesn't specify a variant code, this function returns the empty string.
1742     */
1743    public final String getDisplayVariant() {
1744        return getDisplayVariant(getDefault(Category.DISPLAY));
1745    }
1746
1747    /**
1748     * Returns the full variant name in the specified {@code Locale} for the variant code
1749     * of this {@code Locale}. If there is no matching variant name, the variant code is
1750     * returned.
1751     *
1752     * @since 1.7
1753     */
1754    public String getDisplayVariant(Locale locale) {
1755        String variantCode = baseLocale.getVariant();
1756        if (variantCode.isEmpty()) {
1757            return "";
1758        }
1759
1760        try {
1761            normalizeAndValidateVariant(variantCode);
1762        } catch (IllformedLocaleException ilfe) {
1763            return variantCode;
1764        }
1765
1766        String result = ICU.getDisplayVariant(this, locale);
1767        if (result == null) { // TODO: do we need to do this, or does ICU do it for us?
1768            result = ICU.getDisplayVariant(this, Locale.getDefault());
1769        }
1770
1771        // The "old style" locale constructors allow us to pass in variants that aren't
1772        // valid BCP-47 variant subtags. When that happens, toLanguageTag will not emit
1773        // them. Note that we know variantCode.length() > 0 due to the isEmpty check at
1774        // the beginning of this function.
1775        if (result.isEmpty()) {
1776            return variantCode;
1777        }
1778        return result;
1779    }
1780
1781    private static String normalizeAndValidateVariant(String variant) {
1782        if (variant == null || variant.isEmpty()) {
1783            return "";
1784        }
1785
1786        // Note that unlike extensions, we canonicalize to lower case alphabets
1787        // and underscores instead of hyphens.
1788        final String normalizedVariant = variant.replace('-', '_');
1789        String[] subTags = normalizedVariant.split("_");
1790
1791        for (String subTag : subTags) {
1792            if (!isValidVariantSubtag(subTag)) {
1793                throw new IllformedLocaleException("Invalid variant: " + variant);
1794            }
1795        }
1796
1797        return normalizedVariant;
1798    }
1799
1800    private static boolean isValidVariantSubtag(String subTag) {
1801        // The BCP-47 spec states that :
1802        // - Subtags can be between [5, 8] alphanumeric chars in length.
1803        // - Subtags that start with a number are allowed to be 4 chars in length.
1804        if (subTag.length() >= 5 && subTag.length() <= 8) {
1805            if (isAsciiAlphaNum(subTag)) {
1806                return true;
1807            }
1808        } else if (subTag.length() == 4) {
1809            final char firstChar = subTag.charAt(0);
1810            if ((firstChar >= '0' && firstChar <= '9') && isAsciiAlphaNum(subTag)) {
1811                return true;
1812            }
1813        }
1814
1815        return false;
1816    }
1817
1818    /**
1819     * Returns a name for the locale that is appropriate for display to the
1820     * user. This will be the values returned by getDisplayLanguage(),
1821     * getDisplayScript(), getDisplayCountry(), and getDisplayVariant() assembled
1822     * into a single string. The the non-empty values are used in order,
1823     * with the second and subsequent names in parentheses.  For example:
1824     * <blockquote>
1825     * language (script, country, variant)<br>
1826     * language (country)<br>
1827     * language (variant)<br>
1828     * script (country)<br>
1829     * country<br>
1830     * </blockquote>
1831     * depending on which fields are specified in the locale.  If the
1832     * language, sacript, country, and variant fields are all empty,
1833     * this function returns the empty string.
1834     */
1835    public final String getDisplayName() {
1836        return getDisplayName(getDefault(Category.DISPLAY));
1837    }
1838
1839    /**
1840     * Returns this locale's language name, country name, and variant, localized
1841     * to {@code locale}. The exact output form depends on whether this locale
1842     * corresponds to a specific language, script, country and variant.
1843     *
1844     * <p>For example:
1845     * <ul>
1846     * <li>{@code new Locale("en").getDisplayName(Locale.US)} -> {@code English}
1847     * <li>{@code new Locale("en", "US").getDisplayName(Locale.US)} -> {@code English (United States)}
1848     * <li>{@code new Locale("en", "US", "POSIX").getDisplayName(Locale.US)} -> {@code English (United States,Computer)}
1849     * <li>{@code Locale.fromLanguageTag("zh-Hant-CN").getDisplayName(Locale.US)} -> {@code Chinese (Traditional Han,China)}
1850     * <li>{@code new Locale("en").getDisplayName(Locale.FRANCE)} -> {@code anglais}
1851     * <li>{@code new Locale("en", "US").getDisplayName(Locale.FRANCE)} -> {@code anglais (États-Unis)}
1852     * <li>{@code new Locale("en", "US", "POSIX").getDisplayName(Locale.FRANCE)} -> {@code anglais (États-Unis,informatique)}.
1853     * </ul>
1854     */
1855    public String getDisplayName(Locale locale) {
1856        int count = 0;
1857        StringBuilder buffer = new StringBuilder();
1858        String languageCode = baseLocale.getLanguage();
1859        if (!languageCode.isEmpty()) {
1860            String displayLanguage = getDisplayLanguage(locale);
1861            buffer.append(displayLanguage.isEmpty() ? languageCode : displayLanguage);
1862            ++count;
1863        }
1864        String scriptCode = baseLocale.getScript();
1865        if (!scriptCode.isEmpty()) {
1866            if (count == 1) {
1867                buffer.append(" (");
1868            }
1869            String displayScript = getDisplayScript(locale);
1870            buffer.append(displayScript.isEmpty() ? scriptCode : displayScript);
1871            ++count;
1872        }
1873        String countryCode = baseLocale.getRegion();
1874        if (!countryCode.isEmpty()) {
1875            if (count == 1) {
1876                buffer.append(" (");
1877            } else if (count == 2) {
1878                buffer.append(",");
1879            }
1880            String displayCountry = getDisplayCountry(locale);
1881            buffer.append(displayCountry.isEmpty() ? countryCode : displayCountry);
1882            ++count;
1883        }
1884        String variantCode = baseLocale.getVariant();
1885        if (!variantCode.isEmpty()) {
1886            if (count == 1) {
1887                buffer.append(" (");
1888            } else if (count == 2 || count == 3) {
1889                buffer.append(",");
1890            }
1891            String displayVariant = getDisplayVariant(locale);
1892            buffer.append(displayVariant.isEmpty() ? variantCode : displayVariant);
1893            ++count;
1894        }
1895        if (count > 1) {
1896            buffer.append(")");
1897        }
1898        return buffer.toString();
1899    }
1900
1901    /**
1902     * Overrides Cloneable.
1903     */
1904    public Object clone()
1905    {
1906        try {
1907            Locale that = (Locale)super.clone();
1908            return that;
1909        } catch (CloneNotSupportedException e) {
1910            throw new InternalError();
1911        }
1912    }
1913
1914    /**
1915     * Override hashCode.
1916     * Since Locales are often used in hashtables, caches the value
1917     * for speed.
1918     */
1919    @Override
1920    public int hashCode() {
1921        int hc = hashCodeValue;
1922        if (hc == 0) {
1923            hc = baseLocale.hashCode();
1924            if (localeExtensions != null) {
1925                hc ^= localeExtensions.hashCode();
1926            }
1927            hashCodeValue = hc;
1928        }
1929        return hc;
1930    }
1931
1932    // Overrides
1933
1934    /**
1935     * Returns true if this Locale is equal to another object.  A Locale is
1936     * deemed equal to another Locale with identical language, script, country,
1937     * variant and extensions, and unequal to all other objects.
1938     *
1939     * @return true if this Locale is equal to the specified object.
1940     */
1941    @Override
1942    public boolean equals(Object obj) {
1943        if (this == obj)                      // quick check
1944            return true;
1945        if (!(obj instanceof Locale))
1946            return false;
1947        BaseLocale otherBase = ((Locale)obj).baseLocale;
1948        if (!baseLocale.equals(otherBase)) {
1949            return false;
1950        }
1951        if (localeExtensions == null) {
1952            return ((Locale)obj).localeExtensions == null;
1953        }
1954        return localeExtensions.equals(((Locale)obj).localeExtensions);
1955    }
1956
1957    // ================= privates =====================================
1958
1959    private transient BaseLocale baseLocale;
1960    private transient LocaleExtensions localeExtensions;
1961
1962    /**
1963     * Calculated hashcode
1964     */
1965    private transient volatile int hashCodeValue = 0;
1966
1967    private static Locale defaultLocale = null;
1968    private static Locale defaultDisplayLocale = null;
1969    private static Locale defaultFormatLocale = null;
1970
1971    /**
1972     * Format a list using given pattern strings.
1973     * If either of the patterns is null, then a the list is
1974     * formatted by concatenation with the delimiter ','.
1975     * @param stringList the list of strings to be formatted.
1976     * @param listPattern should create a MessageFormat taking 0-3 arguments
1977     * and formatting them into a list.
1978     * @param listCompositionPattern should take 2 arguments
1979     * and is used by composeList.
1980     * @return a string representing the list.
1981     */
1982    private static String formatList(String[] stringList, String listPattern, String listCompositionPattern) {
1983        // If we have no list patterns, compose the list in a simple,
1984        // non-localized way.
1985        if (listPattern == null || listCompositionPattern == null) {
1986            StringBuffer result = new StringBuffer();
1987            for (int i=0; i<stringList.length; ++i) {
1988                if (i>0) result.append(',');
1989                result.append(stringList[i]);
1990            }
1991            return result.toString();
1992        }
1993
1994        // Compose the list down to three elements if necessary
1995        if (stringList.length > 3) {
1996            MessageFormat format = new MessageFormat(listCompositionPattern);
1997            stringList = composeList(format, stringList);
1998        }
1999
2000        // Rebuild the argument list with the list length as the first element
2001        Object[] args = new Object[stringList.length + 1];
2002        System.arraycopy(stringList, 0, args, 1, stringList.length);
2003        args[0] = new Integer(stringList.length);
2004
2005        // Format it using the pattern in the resource
2006        MessageFormat format = new MessageFormat(listPattern);
2007        return format.format(args);
2008    }
2009
2010    /**
2011     * Given a list of strings, return a list shortened to three elements.
2012     * Shorten it by applying the given format to the first two elements
2013     * recursively.
2014     * @param format a format which takes two arguments
2015     * @param list a list of strings
2016     * @return if the list is three elements or shorter, the same list;
2017     * otherwise, a new list of three elements.
2018     */
2019    private static String[] composeList(MessageFormat format, String[] list) {
2020        if (list.length <= 3) return list;
2021
2022        // Use the given format to compose the first two elements into one
2023        String[] listItems = { list[0], list[1] };
2024        String newItem = format.format(listItems);
2025
2026        // Form a new list one element shorter
2027        String[] newList = new String[list.length-1];
2028        System.arraycopy(list, 2, newList, 1, newList.length-1);
2029        newList[0] = newItem;
2030
2031        // Recurse
2032        return composeList(format, newList);
2033    }
2034
2035    /**
2036     * @serialField language    String
2037     *      language subtag in lower case. (See <a href="java/util/Locale.html#getLanguage()">getLanguage()</a>)
2038     * @serialField country     String
2039     *      country subtag in upper case. (See <a href="java/util/Locale.html#getCountry()">getCountry()</a>)
2040     * @serialField variant     String
2041     *      variant subtags separated by LOWLINE characters. (See <a href="java/util/Locale.html#getVariant()">getVariant()</a>)
2042     * @serialField hashcode    int
2043     *      deprecated, for forward compatibility only
2044     * @serialField script      String
2045     *      script subtag in title case (See <a href="java/util/Locale.html#getScript()">getScript()</a>)
2046     * @serialField extensions  String
2047     *      canonical representation of extensions, that is,
2048     *      BCP47 extensions in alphabetical order followed by
2049     *      BCP47 private use subtags, all in lower case letters
2050     *      separated by HYPHEN-MINUS characters.
2051     *      (See <a href="java/util/Locale.html#getExtensionKeys()">getExtensionKeys()</a>,
2052     *      <a href="java/util/Locale.html#getExtension(char)">getExtension(char)</a>)
2053     */
2054    private static final ObjectStreamField[] serialPersistentFields = {
2055        new ObjectStreamField("language", String.class),
2056        new ObjectStreamField("country", String.class),
2057        new ObjectStreamField("variant", String.class),
2058        new ObjectStreamField("hashcode", int.class),
2059        new ObjectStreamField("script", String.class),
2060        new ObjectStreamField("extensions", String.class),
2061    };
2062
2063    /**
2064     * Serializes this <code>Locale</code> to the specified <code>ObjectOutputStream</code>.
2065     * @param out the <code>ObjectOutputStream</code> to write
2066     * @throws IOException
2067     * @since 1.7
2068     */
2069    private void writeObject(ObjectOutputStream out) throws IOException {
2070        ObjectOutputStream.PutField fields = out.putFields();
2071        fields.put("language", baseLocale.getLanguage());
2072        fields.put("script", baseLocale.getScript());
2073        fields.put("country", baseLocale.getRegion());
2074        fields.put("variant", baseLocale.getVariant());
2075        fields.put("extensions", localeExtensions == null ? "" : localeExtensions.getID());
2076        fields.put("hashcode", -1); // place holder just for backward support
2077        out.writeFields();
2078    }
2079
2080    /**
2081     * Deserializes this <code>Locale</code>.
2082     * @param in the <code>ObjectInputStream</code> to read
2083     * @throws IOException
2084     * @throws ClassNotFoundException
2085     * @throws IllformedLocaleException
2086     * @since 1.7
2087     */
2088    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
2089        ObjectInputStream.GetField fields = in.readFields();
2090        String language = (String)fields.get("language", "");
2091        String script = (String)fields.get("script", "");
2092        String country = (String)fields.get("country", "");
2093        String variant = (String)fields.get("variant", "");
2094        String extStr = (String)fields.get("extensions", "");
2095        baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), script, country, variant);
2096        if (extStr.length() > 0) {
2097            try {
2098                InternalLocaleBuilder bldr = new InternalLocaleBuilder();
2099                bldr.setExtensions(extStr);
2100                localeExtensions = bldr.getLocaleExtensions();
2101            } catch (LocaleSyntaxException e) {
2102                throw new IllformedLocaleException(e.getMessage());
2103            }
2104        } else {
2105            localeExtensions = null;
2106        }
2107    }
2108
2109    /**
2110     * Returns a cached <code>Locale</code> instance equivalent to
2111     * the deserialized <code>Locale</code>. When serialized
2112     * language, country and variant fields read from the object data stream
2113     * are exactly "ja", "JP", "JP" or "th", "TH", "TH" and script/extensions
2114     * fields are empty, this method supplies <code>UNICODE_LOCALE_EXTENSION</code>
2115     * "ca"/"japanese" (calendar type is "japanese") or "nu"/"thai" (number script
2116     * type is "thai"). See <a href="Locale.html#special_cases_constructor"/>Special Cases</a>
2117     * for more information.
2118     *
2119     * @return an instance of <code>Locale</code> equivalent to
2120     * the deserialized <code>Locale</code>.
2121     * @throws java.io.ObjectStreamException
2122     */
2123    private Object readResolve() throws java.io.ObjectStreamException {
2124        return getInstance(baseLocale.getLanguage(), baseLocale.getScript(),
2125                baseLocale.getRegion(), baseLocale.getVariant(), localeExtensions);
2126    }
2127
2128    private static volatile String[] isoLanguages = null;
2129
2130    private static volatile String[] isoCountries = null;
2131
2132    private static String convertOldISOCodes(String language) {
2133        // we accept both the old and the new ISO codes for the languages whose ISO
2134        // codes have changed, but we always store the OLD code, for backward compatibility
2135        language = LocaleUtils.toLowerString(language).intern();
2136        if (language == "he") {
2137            return "iw";
2138        } else if (language == "yi") {
2139            return "ji";
2140        } else if (language == "id") {
2141            return "in";
2142        } else {
2143            return language;
2144        }
2145    }
2146
2147    private static LocaleExtensions getCompatibilityExtensions(String language,
2148                                                               String script,
2149                                                               String country,
2150                                                               String variant) {
2151        LocaleExtensions extensions = null;
2152        // Special cases for backward compatibility support
2153        if (LocaleUtils.caseIgnoreMatch(language, "ja")
2154                && script.length() == 0
2155                && LocaleUtils.caseIgnoreMatch(country, "jp")
2156                && "JP".equals(variant)) {
2157            // ja_JP_JP -> u-ca-japanese (calendar = japanese)
2158            extensions = LocaleExtensions.CALENDAR_JAPANESE;
2159        } else if (LocaleUtils.caseIgnoreMatch(language, "th")
2160                && script.length() == 0
2161                && LocaleUtils.caseIgnoreMatch(country, "th")
2162                && "TH".equals(variant)) {
2163            // th_TH_TH -> u-nu-thai (numbersystem = thai)
2164            extensions = LocaleExtensions.NUMBER_THAI;
2165        }
2166        return extensions;
2167    }
2168
2169    /**
2170     * @hide for internal use only.
2171     */
2172    public static String adjustLanguageCode(String languageCode) {
2173        String adjusted = languageCode.toLowerCase(Locale.US);
2174        // Map new language codes to the obsolete language
2175        // codes so the correct resource bundles will be used.
2176        if (languageCode.equals("he")) {
2177            adjusted = "iw";
2178        } else if (languageCode.equals("id")) {
2179            adjusted = "in";
2180        } else if (languageCode.equals("yi")) {
2181            adjusted = "ji";
2182        }
2183
2184        return adjusted;
2185    }
2186
2187    /**
2188     * Enum for locale categories.  These locale categories are used to get/set
2189     * the default locale for the specific functionality represented by the
2190     * category.
2191     *
2192     * @see #getDefault(Locale.Category)
2193     * @see #setDefault(Locale.Category, Locale)
2194     * @since 1.7
2195     */
2196    public enum Category {
2197
2198        /**
2199         * Category used to represent the default locale for
2200         * displaying user interfaces.
2201         */
2202        DISPLAY("user.language.display",
2203                "user.script.display",
2204                "user.country.display",
2205                "user.variant.display"),
2206
2207        /**
2208         * Category used to represent the default locale for
2209         * formatting dates, numbers, and/or currencies.
2210         */
2211        FORMAT("user.language.format",
2212               "user.script.format",
2213               "user.country.format",
2214               "user.variant.format");
2215
2216        Category(String languageKey, String scriptKey, String countryKey, String variantKey) {
2217            this.languageKey = languageKey;
2218            this.scriptKey = scriptKey;
2219            this.countryKey = countryKey;
2220            this.variantKey = variantKey;
2221        }
2222
2223        final String languageKey;
2224        final String scriptKey;
2225        final String countryKey;
2226        final String variantKey;
2227    }
2228
2229    /**
2230     * <code>Builder</code> is used to build instances of <code>Locale</code>
2231     * from values configured by the setters.  Unlike the <code>Locale</code>
2232     * constructors, the <code>Builder</code> checks if a value configured by a
2233     * setter satisfies the syntax requirements defined by the <code>Locale</code>
2234     * class.  A <code>Locale</code> object created by a <code>Builder</code> is
2235     * well-formed and can be transformed to a well-formed IETF BCP 47 language tag
2236     * without losing information.
2237     *
2238     * <p><b>Note:</b> The <code>Locale</code> class does not provide any
2239     * syntactic restrictions on variant, while BCP 47 requires each variant
2240     * subtag to be 5 to 8 alphanumerics or a single numeric followed by 3
2241     * alphanumerics.  The method <code>setVariant</code> throws
2242     * <code>IllformedLocaleException</code> for a variant that does not satisfy
2243     * this restriction. If it is necessary to support such a variant, use a
2244     * Locale constructor.  However, keep in mind that a <code>Locale</code>
2245     * object created this way might lose the variant information when
2246     * transformed to a BCP 47 language tag.
2247     *
2248     * <p>The following example shows how to create a <code>Locale</code> object
2249     * with the <code>Builder</code>.
2250     * <blockquote>
2251     * <pre>
2252     *     Locale aLocale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build();
2253     * </pre>
2254     * </blockquote>
2255     *
2256     * <p>Builders can be reused; <code>clear()</code> resets all
2257     * fields to their default values.
2258     *
2259     * @see Locale#forLanguageTag
2260     * @since 1.7
2261     */
2262    public static final class Builder {
2263        private final InternalLocaleBuilder localeBuilder;
2264
2265        /**
2266         * Constructs an empty Builder. The default value of all
2267         * fields, extensions, and private use information is the
2268         * empty string.
2269         */
2270        public Builder() {
2271            localeBuilder = new InternalLocaleBuilder();
2272        }
2273
2274        /**
2275         * Resets the <code>Builder</code> to match the provided
2276         * <code>locale</code>.  Existing state is discarded.
2277         *
2278         * <p>All fields of the locale must be well-formed, see {@link Locale}.
2279         *
2280         * <p>Locales with any ill-formed fields cause
2281         * <code>IllformedLocaleException</code> to be thrown, except for the
2282         * following three cases which are accepted for compatibility
2283         * reasons:<ul>
2284         * <li>Locale("ja", "JP", "JP") is treated as "ja-JP-u-ca-japanese"
2285         * <li>Locale("th", "TH", "TH") is treated as "th-TH-u-nu-thai"
2286         * <li>Locale("no", "NO", "NY") is treated as "nn-NO"</ul>
2287         *
2288         * @param locale the locale
2289         * @return This builder.
2290         * @throws IllformedLocaleException if <code>locale</code> has
2291         * any ill-formed fields.
2292         * @throws NullPointerException if <code>locale</code> is null.
2293         */
2294        public Builder setLocale(Locale locale) {
2295            try {
2296                localeBuilder.setLocale(locale.baseLocale, locale.localeExtensions);
2297            } catch (LocaleSyntaxException e) {
2298                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2299            }
2300            return this;
2301        }
2302
2303        /**
2304         * Resets the Builder to match the provided IETF BCP 47
2305         * language tag.  Discards the existing state.  Null and the
2306         * empty string cause the builder to be reset, like {@link
2307         * #clear}.  Grandfathered tags (see {@link
2308         * Locale#forLanguageTag}) are converted to their canonical
2309         * form before being processed.  Otherwise, the language tag
2310         * must be well-formed (see {@link Locale}) or an exception is
2311         * thrown (unlike <code>Locale.forLanguageTag</code>, which
2312         * just discards ill-formed and following portions of the
2313         * tag).
2314         *
2315         * @param languageTag the language tag
2316         * @return This builder.
2317         * @throws IllformedLocaleException if <code>languageTag</code> is ill-formed
2318         * @see Locale#forLanguageTag(String)
2319         */
2320        public Builder setLanguageTag(String languageTag) {
2321            ParseStatus sts = new ParseStatus();
2322            LanguageTag tag = LanguageTag.parse(languageTag, sts);
2323            if (sts.isError()) {
2324                throw new IllformedLocaleException(sts.getErrorMessage(), sts.getErrorIndex());
2325            }
2326            localeBuilder.setLanguageTag(tag);
2327            return this;
2328        }
2329
2330        /**
2331         * Sets the language.  If <code>language</code> is the empty string or
2332         * null, the language in this <code>Builder</code> is removed.  Otherwise,
2333         * the language must be <a href="./Locale.html#def_language">well-formed</a>
2334         * or an exception is thrown.
2335         *
2336         * <p>The typical language value is a two or three-letter language
2337         * code as defined in ISO639.
2338         *
2339         * @param language the language
2340         * @return This builder.
2341         * @throws IllformedLocaleException if <code>language</code> is ill-formed
2342         */
2343        public Builder setLanguage(String language) {
2344            try {
2345                localeBuilder.setLanguage(language);
2346            } catch (LocaleSyntaxException e) {
2347                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2348            }
2349            return this;
2350        }
2351
2352        /**
2353         * Sets the script. If <code>script</code> is null or the empty string,
2354         * the script in this <code>Builder</code> is removed.
2355         * Otherwise, the script must be <a href="./Locale.html#def_script">well-formed</a> or an
2356         * exception is thrown.
2357         *
2358         * <p>The typical script value is a four-letter script code as defined by ISO 15924.
2359         *
2360         * @param script the script
2361         * @return This builder.
2362         * @throws IllformedLocaleException if <code>script</code> is ill-formed
2363         */
2364        public Builder setScript(String script) {
2365            try {
2366                localeBuilder.setScript(script);
2367            } catch (LocaleSyntaxException e) {
2368                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2369            }
2370            return this;
2371        }
2372
2373        /**
2374         * Sets the region.  If region is null or the empty string, the region
2375         * in this <code>Builder</code> is removed.  Otherwise,
2376         * the region must be <a href="./Locale.html#def_region">well-formed</a> or an
2377         * exception is thrown.
2378         *
2379         * <p>The typical region value is a two-letter ISO 3166 code or a
2380         * three-digit UN M.49 area code.
2381         *
2382         * <p>The country value in the <code>Locale</code> created by the
2383         * <code>Builder</code> is always normalized to upper case.
2384         *
2385         * @param region the region
2386         * @return This builder.
2387         * @throws IllformedLocaleException if <code>region</code> is ill-formed
2388         */
2389        public Builder setRegion(String region) {
2390            try {
2391                localeBuilder.setRegion(region);
2392            } catch (LocaleSyntaxException e) {
2393                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2394            }
2395            return this;
2396        }
2397
2398        /**
2399         * Sets the variant.  If variant is null or the empty string, the
2400         * variant in this <code>Builder</code> is removed.  Otherwise, it
2401         * must consist of one or more <a href="./Locale.html#def_variant">well-formed</a>
2402         * subtags, or an exception is thrown.
2403         *
2404         * <p><b>Note:</b> This method checks if <code>variant</code>
2405         * satisfies the IETF BCP 47 variant subtag's syntax requirements,
2406         * and normalizes the value to lowercase letters.  However,
2407         * the <code>Locale</code> class does not impose any syntactic
2408         * restriction on variant, and the variant value in
2409         * <code>Locale</code> is case sensitive.  To set such a variant,
2410         * use a Locale constructor.
2411         *
2412         * @param variant the variant
2413         * @return This builder.
2414         * @throws IllformedLocaleException if <code>variant</code> is ill-formed
2415         */
2416        public Builder setVariant(String variant) {
2417            try {
2418                localeBuilder.setVariant(variant);
2419            } catch (LocaleSyntaxException e) {
2420                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2421            }
2422            return this;
2423        }
2424
2425        /**
2426         * Sets the extension for the given key. If the value is null or the
2427         * empty string, the extension is removed.  Otherwise, the extension
2428         * must be <a href="./Locale.html#def_extensions">well-formed</a> or an exception
2429         * is thrown.
2430         *
2431         * <p><b>Note:</b> The key {@link Locale#UNICODE_LOCALE_EXTENSION
2432         * UNICODE_LOCALE_EXTENSION} ('u') is used for the Unicode locale extension.
2433         * Setting a value for this key replaces any existing Unicode locale key/type
2434         * pairs with those defined in the extension.
2435         *
2436         * <p><b>Note:</b> The key {@link Locale#PRIVATE_USE_EXTENSION
2437         * PRIVATE_USE_EXTENSION} ('x') is used for the private use code. To be
2438         * well-formed, the value for this key needs only to have subtags of one to
2439         * eight alphanumeric characters, not two to eight as in the general case.
2440         *
2441         * @param key the extension key
2442         * @param value the extension value
2443         * @return This builder.
2444         * @throws IllformedLocaleException if <code>key</code> is illegal
2445         * or <code>value</code> is ill-formed
2446         * @see #setUnicodeLocaleKeyword(String, String)
2447         */
2448        public Builder setExtension(char key, String value) {
2449            try {
2450                localeBuilder.setExtension(key, value);
2451            } catch (LocaleSyntaxException e) {
2452                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2453            }
2454            return this;
2455        }
2456
2457        /**
2458         * Sets the Unicode locale keyword type for the given key.  If the type
2459         * is null, the Unicode keyword is removed.  Otherwise, the key must be
2460         * non-null and both key and type must be <a
2461         * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
2462         * is thrown.
2463         *
2464         * <p>Keys and types are converted to lower case.
2465         *
2466         * <p><b>Note</b>:Setting the 'u' extension via {@link #setExtension}
2467         * replaces all Unicode locale keywords with those defined in the
2468         * extension.
2469         *
2470         * @param key the Unicode locale key
2471         * @param type the Unicode locale type
2472         * @return This builder.
2473         * @throws IllformedLocaleException if <code>key</code> or <code>type</code>
2474         * is ill-formed
2475         * @throws NullPointerException if <code>key</code> is null
2476         * @see #setExtension(char, String)
2477         */
2478        public Builder setUnicodeLocaleKeyword(String key, String type) {
2479            try {
2480                localeBuilder.setUnicodeLocaleKeyword(key, type);
2481            } catch (LocaleSyntaxException e) {
2482                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2483            }
2484            return this;
2485        }
2486
2487        /**
2488         * Adds a unicode locale attribute, if not already present, otherwise
2489         * has no effect.  The attribute must not be null and must be <a
2490         * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
2491         * is thrown.
2492         *
2493         * @param attribute the attribute
2494         * @return This builder.
2495         * @throws NullPointerException if <code>attribute</code> is null
2496         * @throws IllformedLocaleException if <code>attribute</code> is ill-formed
2497         * @see #setExtension(char, String)
2498         */
2499        public Builder addUnicodeLocaleAttribute(String attribute) {
2500            try {
2501                localeBuilder.addUnicodeLocaleAttribute(attribute);
2502            } catch (LocaleSyntaxException e) {
2503                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2504            }
2505            return this;
2506        }
2507
2508        /**
2509         * Removes a unicode locale attribute, if present, otherwise has no
2510         * effect.  The attribute must not be null and must be <a
2511         * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
2512         * is thrown.
2513         *
2514         * <p>Attribute comparision for removal is case-insensitive.
2515         *
2516         * @param attribute the attribute
2517         * @return This builder.
2518         * @throws NullPointerException if <code>attribute</code> is null
2519         * @throws IllformedLocaleException if <code>attribute</code> is ill-formed
2520         * @see #setExtension(char, String)
2521         */
2522        public Builder removeUnicodeLocaleAttribute(String attribute) {
2523            try {
2524                localeBuilder.removeUnicodeLocaleAttribute(attribute);
2525            } catch (LocaleSyntaxException e) {
2526                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2527            }
2528            return this;
2529        }
2530
2531        /**
2532         * Resets the builder to its initial, empty state.
2533         *
2534         * @return This builder.
2535         */
2536        public Builder clear() {
2537            localeBuilder.clear();
2538            return this;
2539        }
2540
2541        /**
2542         * Resets the extensions to their initial, empty state.
2543         * Language, script, region and variant are unchanged.
2544         *
2545         * @return This builder.
2546         * @see #setExtension(char, String)
2547         */
2548        public Builder clearExtensions() {
2549            localeBuilder.clearExtensions();
2550            return this;
2551        }
2552
2553        /**
2554         * Returns an instance of <code>Locale</code> created from the fields set
2555         * on this builder.
2556         *
2557         * <p>This applies the conversions listed in {@link Locale#forLanguageTag}
2558         * when constructing a Locale. (Grandfathered tags are handled in
2559         * {@link #setLanguageTag}.)
2560         *
2561         * @return A Locale.
2562         */
2563        public Locale build() {
2564            BaseLocale baseloc = localeBuilder.getBaseLocale();
2565            LocaleExtensions extensions = localeBuilder.getLocaleExtensions();
2566            if (extensions == null && baseloc.getVariant().length() > 0) {
2567                extensions = getCompatibilityExtensions(baseloc.getLanguage(), baseloc.getScript(),
2568                        baseloc.getRegion(), baseloc.getVariant());
2569            }
2570            return Locale.getInstance(baseloc, extensions);
2571        }
2572    }
2573}
2574