Locale.java revision 2c87ad3a45cecf9e344487cad1abfdebe79f2c7c
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    }
877
878    /**
879     * Sets the default locale for the specified Category for this instance
880     * of the Java Virtual Machine. This does not affect the host locale.
881     * <p>
882     * If there is a security manager, its checkPermission method is called
883     * with a PropertyPermission("user.language", "write") permission before
884     * the default locale is changed.
885     * <p>
886     * The Java Virtual Machine sets the default locale during startup based
887     * on the host environment. It is used by many locale-sensitive methods
888     * if no locale is explicitly specified.
889     * <p>
890     * Since changing the default locale may affect many different areas of
891     * functionality, this method should only be used if the caller is
892     * prepared to reinitialize locale-sensitive code running within the
893     * same Java Virtual Machine.
894     * <p>
895     *
896     * @param category - the specified category to set the default locale
897     * @param newLocale - the new default locale
898     * @throws SecurityException - if a security manager exists and its
899     *     checkPermission method doesn't allow the operation.
900     * @throws NullPointerException - if category and/or newLocale is null
901     * @see SecurityManager#checkPermission(java.security.Permission)
902     * @see PropertyPermission
903     * @see #getDefault(Locale.Category)
904     * @since 1.7
905     */
906    public static synchronized void setDefault(Locale.Category category,
907        Locale newLocale) {
908        if (category == null)
909            throw new NullPointerException("Category cannot be NULL");
910        if (newLocale == null)
911            throw new NullPointerException("Can't set default locale to NULL");
912
913        SecurityManager sm = System.getSecurityManager();
914        if (sm != null) sm.checkPermission(new PropertyPermission
915                        ("user.language", "write"));
916        switch (category) {
917        case DISPLAY:
918            defaultDisplayLocale = newLocale;
919            break;
920        case FORMAT:
921            defaultFormatLocale = newLocale;
922            break;
923        default:
924            assert false: "Unknown Category";
925        }
926    }
927
928    /**
929     * Returns an array of all installed locales.
930     * The returned array represents the union of locales supported
931     * by the Java runtime environment and by installed
932     * {@link java.util.spi.LocaleServiceProvider LocaleServiceProvider}
933     * implementations.  It must contain at least a <code>Locale</code>
934     * instance equal to {@link java.util.Locale#US Locale.US}.
935     *
936     * @return An array of installed locales.
937     */
938    public static Locale[] getAvailableLocales() {
939        return LocaleServiceProviderPool.getAllAvailableLocales();
940    }
941
942    /**
943     * Returns a list of all 2-letter country codes defined in ISO 3166.
944     * Can be used to create Locales.
945     * <p>
946     * <b>Note:</b> The <code>Locale</code> class also supports other codes for
947     * country (region), such as 3-letter numeric UN M.49 area codes.
948     * Therefore, the list returned by this method does not contain ALL valid
949     * codes that can be used to create Locales.
950     */
951    public static String[] getISOCountries() {
952        // Android-changed: Use ICU.
953        return ICU.getISOCountries();
954    }
955
956    /**
957     * Returns a list of all 2-letter language codes defined in ISO 639.
958     * Can be used to create Locales.
959     * <p>
960     * <b>Note:</b>
961     * <ul>
962     * <li>ISO 639 is not a stable standard&mdash; some languages' codes have changed.
963     * The list this function returns includes both the new and the old codes for the
964     * languages whose codes have changed.
965     * <li>The <code>Locale</code> class also supports language codes up to
966     * 8 characters in length.  Therefore, the list returned by this method does
967     * not contain ALL valid codes that can be used to create Locales.
968     * </ul>
969     */
970    public static String[] getISOLanguages() {
971        // Android-changed: Use ICU.
972        return ICU.getISOLanguages();
973    }
974
975    /**
976     * Returns the language code of this Locale.
977     *
978     * <p><b>Note:</b> ISO 639 is not a stable standard&mdash; some languages' codes have changed.
979     * Locale's constructor recognizes both the new and the old codes for the languages
980     * whose codes have changed, but this function always returns the old code.  If you
981     * want to check for a specific language whose code has changed, don't do
982     * <pre>
983     * if (locale.getLanguage().equals("he")) // BAD!
984     *    ...
985     * </pre>
986     * Instead, do
987     * <pre>
988     * if (locale.getLanguage().equals(new Locale("he").getLanguage()))
989     *    ...
990     * </pre>
991     * @return The language code, or the empty string if none is defined.
992     * @see #getDisplayLanguage
993     */
994    public String getLanguage() {
995        return baseLocale.getLanguage();
996    }
997
998    /**
999     * Returns the script for this locale, which should
1000     * either be the empty string or an ISO 15924 4-letter script
1001     * code. The first letter is uppercase and the rest are
1002     * lowercase, for example, 'Latn', 'Cyrl'.
1003     *
1004     * @return The script code, or the empty string if none is defined.
1005     * @see #getDisplayScript
1006     * @since 1.7
1007     */
1008    public String getScript() {
1009        return baseLocale.getScript();
1010    }
1011
1012    /**
1013     * Returns the country/region code for this locale, which should
1014     * either be the empty string, an uppercase ISO 3166 2-letter code,
1015     * or a UN M.49 3-digit code.
1016     *
1017     * @return The country/region code, or the empty string if none is defined.
1018     * @see #getDisplayCountry
1019     */
1020    public String getCountry() {
1021        return baseLocale.getRegion();
1022    }
1023
1024    /**
1025     * Returns the variant code for this locale.
1026     *
1027     * @return The variant code, or the empty string if none is defined.
1028     * @see #getDisplayVariant
1029     */
1030    public String getVariant() {
1031        return baseLocale.getVariant();
1032    }
1033
1034    /**
1035     * Returns the extension (or private use) value associated with
1036     * the specified key, or null if there is no extension
1037     * associated with the key. To be well-formed, the key must be one
1038     * of <code>[0-9A-Za-z]</code>. Keys are case-insensitive, so
1039     * for example 'z' and 'Z' represent the same extension.
1040     *
1041     * @param key the extension key
1042     * @return The extension, or null if this locale defines no
1043     * extension for the specified key.
1044     * @throws IllegalArgumentException if key is not well-formed
1045     * @see #PRIVATE_USE_EXTENSION
1046     * @see #UNICODE_LOCALE_EXTENSION
1047     * @since 1.7
1048     */
1049    public String getExtension(char key) {
1050        if (!LocaleExtensions.isValidKey(key)) {
1051            throw new IllegalArgumentException("Ill-formed extension key: " + key);
1052        }
1053        return (localeExtensions == null) ? null : localeExtensions.getExtensionValue(key);
1054    }
1055
1056    /**
1057     * Returns the set of extension keys associated with this locale, or the
1058     * empty set if it has no extensions. The returned set is unmodifiable.
1059     * The keys will all be lower-case.
1060     *
1061     * @return The set of extension keys, or the empty set if this locale has
1062     * no extensions.
1063     * @since 1.7
1064     */
1065    public Set<Character> getExtensionKeys() {
1066        if (localeExtensions == null) {
1067            return Collections.emptySet();
1068        }
1069        return localeExtensions.getKeys();
1070    }
1071
1072    /**
1073     * Returns the set of unicode locale attributes associated with
1074     * this locale, or the empty set if it has no attributes. The
1075     * returned set is unmodifiable.
1076     *
1077     * @return The set of attributes.
1078     * @since 1.7
1079     */
1080    public Set<String> getUnicodeLocaleAttributes() {
1081        if (localeExtensions == null) {
1082            return Collections.emptySet();
1083        }
1084        return localeExtensions.getUnicodeLocaleAttributes();
1085    }
1086
1087    /**
1088     * Returns the Unicode locale type associated with the specified Unicode locale key
1089     * for this locale. Returns the empty string for keys that are defined with no type.
1090     * Returns null if the key is not defined. Keys are case-insensitive. The key must
1091     * be two alphanumeric characters ([0-9a-zA-Z]), or an IllegalArgumentException is
1092     * thrown.
1093     *
1094     * @param key the Unicode locale key
1095     * @return The Unicode locale type associated with the key, or null if the
1096     * locale does not define the key.
1097     * @throws IllegalArgumentException if the key is not well-formed
1098     * @throws NullPointerException if <code>key</code> is null
1099     * @since 1.7
1100     */
1101    public String getUnicodeLocaleType(String key) {
1102        if (!UnicodeLocaleExtension.isKey(key)) {
1103            throw new IllegalArgumentException("Ill-formed Unicode locale key: " + key);
1104        }
1105        return (localeExtensions == null) ? null : localeExtensions.getUnicodeLocaleType(key);
1106    }
1107
1108    /**
1109     * Returns the set of Unicode locale keys defined by this locale, or the empty set if
1110     * this locale has none.  The returned set is immutable.  Keys are all lower case.
1111     *
1112     * @return The set of Unicode locale keys, or the empty set if this locale has
1113     * no Unicode locale keywords.
1114     * @since 1.7
1115     */
1116    public Set<String> getUnicodeLocaleKeys() {
1117        if (localeExtensions == null) {
1118            return Collections.emptySet();
1119        }
1120        return localeExtensions.getUnicodeLocaleKeys();
1121    }
1122
1123    /**
1124     * Package locale method returning the Locale's BaseLocale,
1125     * used by ResourceBundle
1126     * @return base locale of this Locale
1127     */
1128    BaseLocale getBaseLocale() {
1129        return baseLocale;
1130    }
1131
1132    /**
1133     * Package private method returning the Locale's LocaleExtensions,
1134     * used by ResourceBundle.
1135     * @return locale exnteions of this Locale,
1136     *         or {@code null} if no extensions are defined
1137     */
1138     LocaleExtensions getLocaleExtensions() {
1139         return localeExtensions;
1140     }
1141
1142    /**
1143     * Returns a string representation of this <code>Locale</code>
1144     * object, consisting of language, country, variant, script,
1145     * and extensions as below:
1146     * <p><blockquote>
1147     * language + "_" + country + "_" + (variant + "_#" | "#") + script + "-" + extensions
1148     * </blockquote>
1149     *
1150     * Language is always lower case, country is always upper case, script is always title
1151     * case, and extensions are always lower case.  Extensions and private use subtags
1152     * will be in canonical order as explained in {@link #toLanguageTag}.
1153     *
1154     * <p>When the locale has neither script nor extensions, the result is the same as in
1155     * Java 6 and prior.
1156     *
1157     * <p>If both the language and country fields are missing, this function will return
1158     * the empty string, even if the variant, script, or extensions field is present (you
1159     * can't have a locale with just a variant, the variant must accompany a well-formed
1160     * language or country code).
1161     *
1162     * <p>If script or extensions are present and variant is missing, no underscore is
1163     * added before the "#".
1164     *
1165     * <p>This behavior is designed to support debugging and to be compatible with
1166     * previous uses of <code>toString</code> that expected language, country, and variant
1167     * fields only.  To represent a Locale as a String for interchange purposes, use
1168     * {@link #toLanguageTag}.
1169     *
1170     * <p>Examples: <ul><tt>
1171     * <li>en
1172     * <li>de_DE
1173     * <li>_GB
1174     * <li>en_US_WIN
1175     * <li>de__POSIX
1176     * <li>zh_CN_#Hans
1177     * <li>zh_TW_#Hant-x-java
1178     * <li>th_TH_TH_#u-nu-thai</tt></ul>
1179     *
1180     * @return A string representation of the Locale, for debugging.
1181     * @see #getDisplayName
1182     * @see #toLanguageTag
1183     */
1184    @Override
1185    public final String toString() {
1186        boolean l = (baseLocale.getLanguage().length() != 0);
1187        boolean s = (baseLocale.getScript().length() != 0);
1188        boolean r = (baseLocale.getRegion().length() != 0);
1189        boolean v = (baseLocale.getVariant().length() != 0);
1190        boolean e = (localeExtensions != null && localeExtensions.getID().length() != 0);
1191
1192        StringBuilder result = new StringBuilder(baseLocale.getLanguage());
1193        if (r || (l && (v || s || e))) {
1194            result.append('_')
1195                .append(baseLocale.getRegion()); // This may just append '_'
1196        }
1197        if (v && (l || r)) {
1198            result.append('_')
1199                .append(baseLocale.getVariant());
1200        }
1201
1202        if (s && (l || r)) {
1203            result.append("_#")
1204                .append(baseLocale.getScript());
1205        }
1206
1207        if (e && (l || r)) {
1208            result.append('_');
1209            if (!s) {
1210                result.append('#');
1211            }
1212            result.append(localeExtensions.getID());
1213        }
1214
1215        return result.toString();
1216    }
1217
1218    /**
1219     * Returns a well-formed IETF BCP 47 language tag representing
1220     * this locale.
1221     *
1222     * <p>If this <code>Locale</code> has a language, country, or
1223     * variant that does not satisfy the IETF BCP 47 language tag
1224     * syntax requirements, this method handles these fields as
1225     * described below:
1226     *
1227     * <p><b>Language:</b> If language is empty, or not <a
1228     * href="#def_language" >well-formed</a> (for example "a" or
1229     * "e2"), it will be emitted as "und" (Undetermined).
1230     *
1231     * <p><b>Country:</b> If country is not <a
1232     * href="#def_region">well-formed</a> (for example "12" or "USA"),
1233     * it will be omitted.
1234     *
1235     * <p><b>Variant:</b> If variant <b>is</b> <a
1236     * href="#def_variant">well-formed</a>, each sub-segment
1237     * (delimited by '-' or '_') is emitted as a subtag.  Otherwise:
1238     * <ul>
1239     *
1240     * <li>if all sub-segments match <code>[0-9a-zA-Z]{1,8}</code>
1241     * (for example "WIN" or "Oracle_JDK_Standard_Edition"), the first
1242     * ill-formed sub-segment and all following will be appended to
1243     * the private use subtag.  The first appended subtag will be
1244     * "lvariant", followed by the sub-segments in order, separated by
1245     * hyphen. For example, "x-lvariant-WIN",
1246     * "Oracle-x-lvariant-JDK-Standard-Edition".
1247     *
1248     * <li>if any sub-segment does not match
1249     * <code>[0-9a-zA-Z]{1,8}</code>, the variant will be truncated
1250     * and the problematic sub-segment and all following sub-segments
1251     * will be omitted.  If the remainder is non-empty, it will be
1252     * emitted as a private use subtag as above (even if the remainder
1253     * turns out to be well-formed).  For example,
1254     * "Solaris_isjustthecoolestthing" is emitted as
1255     * "x-lvariant-Solaris", not as "solaris".</li></ul>
1256     *
1257     * <p><b>Special Conversions:</b> Java supports some old locale
1258     * representations, including deprecated ISO language codes,
1259     * for compatibility. This method performs the following
1260     * conversions:
1261     * <ul>
1262     *
1263     * <li>Deprecated ISO language codes "iw", "ji", and "in" are
1264     * converted to "he", "yi", and "id", respectively.
1265     *
1266     * <li>A locale with language "no", country "NO", and variant
1267     * "NY", representing Norwegian Nynorsk (Norway), is converted
1268     * to a language tag "nn-NO".</li></ul>
1269     *
1270     * <p><b>Note:</b> Although the language tag created by this
1271     * method is well-formed (satisfies the syntax requirements
1272     * defined by the IETF BCP 47 specification), it is not
1273     * necessarily a valid BCP 47 language tag.  For example,
1274     * <pre>
1275     *   new Locale("xx", "YY").toLanguageTag();</pre>
1276     *
1277     * will return "xx-YY", but the language subtag "xx" and the
1278     * region subtag "YY" are invalid because they are not registered
1279     * in the IANA Language Subtag Registry.
1280     *
1281     * @return a BCP47 language tag representing the locale
1282     * @see #forLanguageTag(String)
1283     * @since 1.7
1284     */
1285    public String toLanguageTag() {
1286        LanguageTag tag = LanguageTag.parseLocale(baseLocale, localeExtensions);
1287        StringBuilder buf = new StringBuilder();
1288
1289        String subtag = tag.getLanguage();
1290        if (subtag.length() > 0) {
1291            buf.append(LanguageTag.canonicalizeLanguage(subtag));
1292        }
1293
1294        subtag = tag.getScript();
1295        if (subtag.length() > 0) {
1296            buf.append(LanguageTag.SEP);
1297            buf.append(LanguageTag.canonicalizeScript(subtag));
1298        }
1299
1300        subtag = tag.getRegion();
1301        if (subtag.length() > 0) {
1302            buf.append(LanguageTag.SEP);
1303            buf.append(LanguageTag.canonicalizeRegion(subtag));
1304        }
1305
1306        List<String>subtags = tag.getVariants();
1307        for (String s : subtags) {
1308            buf.append(LanguageTag.SEP);
1309            // preserve casing
1310            buf.append(s);
1311        }
1312
1313        subtags = tag.getExtensions();
1314        for (String s : subtags) {
1315            buf.append(LanguageTag.SEP);
1316            buf.append(LanguageTag.canonicalizeExtension(s));
1317        }
1318
1319        subtag = tag.getPrivateuse();
1320        if (subtag.length() > 0) {
1321            if (buf.length() > 0) {
1322                buf.append(LanguageTag.SEP);
1323            }
1324            buf.append(LanguageTag.PRIVATEUSE).append(LanguageTag.SEP);
1325            // preserve casing
1326            buf.append(subtag);
1327        }
1328
1329        return buf.toString();
1330    }
1331
1332    /**
1333     * Returns a locale for the specified IETF BCP 47 language tag string.
1334     *
1335     * <p>If the specified language tag contains any ill-formed subtags,
1336     * the first such subtag and all following subtags are ignored.  Compare
1337     * to {@link Locale.Builder#setLanguageTag} which throws an exception
1338     * in this case.
1339     *
1340     * <p>The following <b>conversions</b> are performed:<ul>
1341     *
1342     * <li>The language code "und" is mapped to language "".
1343     *
1344     * <li>The language codes "he", "yi", and "id" are mapped to "iw",
1345     * "ji", and "in" respectively. (This is the same canonicalization
1346     * that's done in Locale's constructors.)
1347     *
1348     * <li>The portion of a private use subtag prefixed by "lvariant",
1349     * if any, is removed and appended to the variant field in the
1350     * result locale (without case normalization).  If it is then
1351     * empty, the private use subtag is discarded:
1352     *
1353     * <pre>
1354     *     Locale loc;
1355     *     loc = Locale.forLanguageTag("en-US-x-lvariant-POSIX");
1356     *     loc.getVariant(); // returns "POSIX"
1357     *     loc.getExtension('x'); // returns null
1358     *
1359     *     loc = Locale.forLanguageTag("de-POSIX-x-URP-lvariant-Abc-Def");
1360     *     loc.getVariant(); // returns "POSIX_Abc_Def"
1361     *     loc.getExtension('x'); // returns "urp"
1362     * </pre>
1363     *
1364     * <li>When the languageTag argument contains an extlang subtag,
1365     * the first such subtag is used as the language, and the primary
1366     * language subtag and other extlang subtags are ignored:
1367     *
1368     * <pre>
1369     *     Locale.forLanguageTag("ar-aao").getLanguage(); // returns "aao"
1370     *     Locale.forLanguageTag("en-abc-def-us").toString(); // returns "abc_US"
1371     * </pre>
1372     *
1373     * <li>Case is normalized except for variant tags, which are left
1374     * unchanged.  Language is normalized to lower case, script to
1375     * title case, country to upper case, and extensions to lower
1376     * case.
1377     *
1378     * <li>If, after processing, the locale would exactly match either
1379     * ja_JP_JP or th_TH_TH with no extensions, the appropriate
1380     * extensions are added as though the constructor had been called:
1381     *
1382     * <pre>
1383     *    Locale.forLanguageTag("ja-JP-x-lvariant-JP").toLanguageTag();
1384     *    // returns "ja-JP-u-ca-japanese-x-lvariant-JP"
1385     *    Locale.forLanguageTag("th-TH-x-lvariant-TH").toLanguageTag();
1386     *    // returns "th-TH-u-nu-thai-x-lvariant-TH"
1387     * <pre></ul>
1388     *
1389     * <p>This implements the 'Language-Tag' production of BCP47, and
1390     * so supports grandfathered (regular and irregular) as well as
1391     * private use language tags.  Stand alone private use tags are
1392     * represented as empty language and extension 'x-whatever',
1393     * and grandfathered tags are converted to their canonical replacements
1394     * where they exist.
1395     *
1396     * <p>Grandfathered tags with canonical replacements are as follows:
1397     *
1398     * <table>
1399     * <tbody align="center">
1400     * <tr><th>grandfathered tag</th><th>&nbsp;</th><th>modern replacement</th></tr>
1401     * <tr><td>art-lojban</td><td>&nbsp;</td><td>jbo</td></tr>
1402     * <tr><td>i-ami</td><td>&nbsp;</td><td>ami</td></tr>
1403     * <tr><td>i-bnn</td><td>&nbsp;</td><td>bnn</td></tr>
1404     * <tr><td>i-hak</td><td>&nbsp;</td><td>hak</td></tr>
1405     * <tr><td>i-klingon</td><td>&nbsp;</td><td>tlh</td></tr>
1406     * <tr><td>i-lux</td><td>&nbsp;</td><td>lb</td></tr>
1407     * <tr><td>i-navajo</td><td>&nbsp;</td><td>nv</td></tr>
1408     * <tr><td>i-pwn</td><td>&nbsp;</td><td>pwn</td></tr>
1409     * <tr><td>i-tao</td><td>&nbsp;</td><td>tao</td></tr>
1410     * <tr><td>i-tay</td><td>&nbsp;</td><td>tay</td></tr>
1411     * <tr><td>i-tsu</td><td>&nbsp;</td><td>tsu</td></tr>
1412     * <tr><td>no-bok</td><td>&nbsp;</td><td>nb</td></tr>
1413     * <tr><td>no-nyn</td><td>&nbsp;</td><td>nn</td></tr>
1414     * <tr><td>sgn-BE-FR</td><td>&nbsp;</td><td>sfb</td></tr>
1415     * <tr><td>sgn-BE-NL</td><td>&nbsp;</td><td>vgt</td></tr>
1416     * <tr><td>sgn-CH-DE</td><td>&nbsp;</td><td>sgg</td></tr>
1417     * <tr><td>zh-guoyu</td><td>&nbsp;</td><td>cmn</td></tr>
1418     * <tr><td>zh-hakka</td><td>&nbsp;</td><td>hak</td></tr>
1419     * <tr><td>zh-min-nan</td><td>&nbsp;</td><td>nan</td></tr>
1420     * <tr><td>zh-xiang</td><td>&nbsp;</td><td>hsn</td></tr>
1421     * </tbody>
1422     * </table>
1423     *
1424     * <p>Grandfathered tags with no modern replacement will be
1425     * converted as follows:
1426     *
1427     * <table>
1428     * <tbody align="center">
1429     * <tr><th>grandfathered tag</th><th>&nbsp;</th><th>converts to</th></tr>
1430     * <tr><td>cel-gaulish</td><td>&nbsp;</td><td>xtg-x-cel-gaulish</td></tr>
1431     * <tr><td>en-GB-oed</td><td>&nbsp;</td><td>en-GB-x-oed</td></tr>
1432     * <tr><td>i-default</td><td>&nbsp;</td><td>en-x-i-default</td></tr>
1433     * <tr><td>i-enochian</td><td>&nbsp;</td><td>und-x-i-enochian</td></tr>
1434     * <tr><td>i-mingo</td><td>&nbsp;</td><td>see-x-i-mingo</td></tr>
1435     * <tr><td>zh-min</td><td>&nbsp;</td><td>nan-x-zh-min</td></tr>
1436     * </tbody>
1437     * </table>
1438     *
1439     * <p>For a list of all grandfathered tags, see the
1440     * IANA Language Subtag Registry (search for "Type: grandfathered").
1441     *
1442     * <p><b>Note</b>: there is no guarantee that <code>toLanguageTag</code>
1443     * and <code>forLanguageTag</code> will round-trip.
1444     *
1445     * @param languageTag the language tag
1446     * @return The locale that best represents the language tag.
1447     * @throws NullPointerException if <code>languageTag</code> is <code>null</code>
1448     * @see #toLanguageTag()
1449     * @see java.util.Locale.Builder#setLanguageTag(String)
1450     * @since 1.7
1451     */
1452    public static Locale forLanguageTag(String languageTag) {
1453        LanguageTag tag = LanguageTag.parse(languageTag, null);
1454        InternalLocaleBuilder bldr = new InternalLocaleBuilder();
1455        bldr.setLanguageTag(tag);
1456        BaseLocale base = bldr.getBaseLocale();
1457        LocaleExtensions exts = bldr.getLocaleExtensions();
1458        if (exts == null && base.getVariant().length() > 0) {
1459            exts = getCompatibilityExtensions(base.getLanguage(), base.getScript(),
1460                                              base.getRegion(), base.getVariant());
1461        }
1462        return getInstance(base, exts);
1463    }
1464
1465    /**
1466     * Returns a three-letter abbreviation of this locale's language.
1467     * If the language matches an ISO 639-1 two-letter code, the
1468     * corresponding ISO 639-2/T three-letter lowercase code is
1469     * returned.  The ISO 639-2 language codes can be found on-line,
1470     * see "Codes for the Representation of Names of Languages Part 2:
1471     * Alpha-3 Code".  If the locale specifies a three-letter
1472     * language, the language is returned as is.  If the locale does
1473     * not specify a language the empty string is returned.
1474     *
1475     * @return A three-letter abbreviation of this locale's language.
1476     * @exception MissingResourceException Throws MissingResourceException if
1477     * three-letter language abbreviation is not available for this locale.
1478     */
1479    public String getISO3Language() throws MissingResourceException {
1480        // Android-changed: Use ICU.getIso3Language. Also return "" for empty languages
1481        // for the sake of backwards compatibility.
1482        String lang = baseLocale.getLanguage();
1483        if (lang.length() == 3) {
1484            return lang;
1485        } else if (lang.isEmpty()) {
1486            return "";
1487        }
1488
1489        String language3 = ICU.getISO3Language(lang);
1490        if (language3.isEmpty()) {
1491            throw new MissingResourceException("Couldn't find 3-letter language code for "
1492                    + lang, "FormatData_" + toString(), "ShortLanguage");
1493        }
1494
1495        return language3;
1496    }
1497
1498    /**
1499     * Returns a three-letter abbreviation for this locale's country.
1500     * If the country matches an ISO 3166-1 alpha-2 code, the
1501     * corresponding ISO 3166-1 alpha-3 uppercase code is returned.
1502     * If the locale doesn't specify a country, this will be the empty
1503     * string.
1504     *
1505     * <p>The ISO 3166-1 codes can be found on-line.
1506     *
1507     * @return A three-letter abbreviation of this locale's country.
1508     * @exception MissingResourceException Throws MissingResourceException if the
1509     * three-letter country abbreviation is not available for this locale.
1510     */
1511    public String getISO3Country() throws MissingResourceException {
1512        // Android changed: Use.getIso3Country. Also return "" for missing regions.
1513        final String region = baseLocale.getRegion();
1514        // Note that this will return an UN.M49 region code
1515        if (region.length() == 3) {
1516            return baseLocale.getRegion();
1517        } else if (region.isEmpty()) {
1518            return "";
1519        }
1520
1521        // Prefix "en-" because ICU doesn't really care about what the language is.
1522        String country3 = ICU.getISO3Country("en-" + region);
1523        if (country3 == null) {
1524            throw new MissingResourceException("Couldn't find 3-letter country code for "
1525                    + baseLocale.getRegion(), "FormatData_" + toString(), "ShortCountry");
1526        }
1527        return country3;
1528    }
1529
1530    /**
1531     * Returns a name for the locale's language that is appropriate for display to the
1532     * user.
1533     * If possible, the name returned will be localized for the default locale.
1534     * For example, if the locale is fr_FR and the default locale
1535     * is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and
1536     * the default locale is fr_FR, getDisplayLanguage() will return "anglais".
1537     * If the name returned cannot be localized for the default locale,
1538     * (say, we don't have a Japanese name for Croatian),
1539     * this function falls back on the English name, and uses the ISO code as a last-resort
1540     * value.  If the locale doesn't specify a language, this function returns the empty string.
1541     */
1542    public final String getDisplayLanguage() {
1543        return getDisplayLanguage(getDefault(Category.DISPLAY));
1544    }
1545
1546    /**
1547     * Returns the name of this locale's language, localized to {@code locale}.
1548     * If the language name is unknown, the language code is returned.
1549     */
1550    public String getDisplayLanguage(Locale locale) {
1551        String languageCode = baseLocale.getLanguage();
1552        if (languageCode.isEmpty()) {
1553            return "";
1554        }
1555
1556        // Hacks for backward compatibility.
1557        //
1558        // Our language tag will contain "und" if the languageCode is invalid
1559        // or missing. ICU will then return "langue indéterminée" or the equivalent
1560        // display language for the indeterminate language code.
1561        //
1562        // Sigh... ugh... and what not.
1563        final String normalizedLanguage = normalizeAndValidateLanguage(
1564                languageCode, false /* strict */);
1565        if (UNDETERMINED_LANGUAGE.equals(normalizedLanguage)) {
1566            return languageCode;
1567        }
1568
1569        // TODO: We need a new hack or a complete fix for http://b/8049507 --- We would
1570        // cover the frameworks' tracks when they were using "tl" instead of "fil".
1571        String result = ICU.getDisplayLanguage(this, locale);
1572        if (result == null) { // TODO: do we need to do this, or does ICU do it for us?
1573            result = ICU.getDisplayLanguage(this, Locale.getDefault());
1574        }
1575        return result;
1576    }
1577
1578    private static String normalizeAndValidateLanguage(String language, boolean strict) {
1579        if (language == null || language.isEmpty()) {
1580            return "";
1581        }
1582
1583        final String lowercaseLanguage = language.toLowerCase(Locale.ROOT);
1584        if (!isValidBcp47Alpha(lowercaseLanguage, 2, 3)) {
1585            if (strict) {
1586                throw new IllformedLocaleException("Invalid language: " + language);
1587            } else {
1588                return UNDETERMINED_LANGUAGE;
1589            }
1590        }
1591
1592        return lowercaseLanguage;
1593    }
1594
1595    /*
1596     * Checks whether a given string is an ASCII alphanumeric string.
1597     */
1598    private static boolean isAsciiAlphaNum(String string) {
1599        for (int i = 0; i < string.length(); i++) {
1600            final char character = string.charAt(i);
1601            if (!(character >= 'a' && character <= 'z' ||
1602                    character >= 'A' && character <= 'Z' ||
1603                    character >= '0' && character <= '9')) {
1604                return false;
1605            }
1606        }
1607
1608        return true;
1609    }
1610
1611    /**
1612     * Returns a name for the the locale's script that is appropriate for display to
1613     * the user. If possible, the name will be localized for the default locale.  Returns
1614     * the empty string if this locale doesn't specify a script code.
1615     *
1616     * @return the display name of the script code for the current default locale
1617     * @since 1.7
1618     */
1619    public String getDisplayScript() {
1620        return getDisplayScript(getDefault());
1621    }
1622
1623    /**
1624     * Returns the name of this locale's script code, localized to {@link Locale}. If the
1625     * script code is unknown, the return value of this method is the same as that of
1626     * {@link #getScript()}.
1627     *
1628     * @since 1.7
1629     */
1630    public String getDisplayScript(Locale locale) {
1631        String scriptCode = baseLocale.getScript();
1632        if (scriptCode.isEmpty()) {
1633            return "";
1634        }
1635
1636        String result = ICU.getDisplayScript(this, locale);
1637        if (result == null) { // TODO: do we need to do this, or does ICU do it for us?
1638            result = ICU.getDisplayScript(this, Locale.getDefault());
1639        }
1640
1641        return result;
1642
1643    }
1644
1645    /**
1646     * Returns a name for the locale's country that is appropriate for display to the
1647     * user.
1648     * If possible, the name returned will be localized for the default locale.
1649     * For example, if the locale is fr_FR and the default locale
1650     * is en_US, getDisplayCountry() will return "France"; if the locale is en_US and
1651     * the default locale is fr_FR, getDisplayCountry() will return "Etats-Unis".
1652     * If the name returned cannot be localized for the default locale,
1653     * (say, we don't have a Japanese name for Croatia),
1654     * this function falls back on the English name, and uses the ISO code as a last-resort
1655     * value.  If the locale doesn't specify a country, this function returns the empty string.
1656     */
1657    public final String getDisplayCountry() {
1658        return getDisplayCountry(getDefault(Category.DISPLAY));
1659    }
1660    /**
1661     * Returns the name of this locale's country, localized to {@code locale}.
1662     * Returns the empty string if this locale does not correspond to a specific
1663     * country.
1664     */
1665    public String getDisplayCountry(Locale locale) {
1666        String countryCode = baseLocale.getRegion();
1667        if (countryCode.isEmpty()) {
1668            return "";
1669        }
1670
1671        final String normalizedRegion = normalizeAndValidateRegion(
1672                countryCode, false /* strict */);
1673        if (normalizedRegion.isEmpty()) {
1674            return countryCode;
1675        }
1676
1677        String result = ICU.getDisplayCountry(this, locale);
1678        if (result == null) { // TODO: do we need to do this, or does ICU do it for us?
1679            result = ICU.getDisplayCountry(this, Locale.getDefault());
1680        }
1681        return result;
1682    }
1683
1684    private static String normalizeAndValidateRegion(String region, boolean strict) {
1685        if (region == null || region.isEmpty()) {
1686            return "";
1687        }
1688
1689        final String uppercaseRegion = region.toUpperCase(Locale.ROOT);
1690        if (!isValidBcp47Alpha(uppercaseRegion, 2, 2) &&
1691                !isUnM49AreaCode(uppercaseRegion)) {
1692            if (strict) {
1693                throw new IllformedLocaleException("Invalid region: " + region);
1694            } else {
1695                return "";
1696            }
1697        }
1698
1699        return uppercaseRegion;
1700    }
1701
1702    private static boolean isValidBcp47Alpha(String string, int lowerBound, int upperBound) {
1703        final int length = string.length();
1704        if (length < lowerBound || length > upperBound) {
1705            return false;
1706        }
1707
1708        for (int i = 0; i < length; ++i) {
1709            final char character = string.charAt(i);
1710            if (!(character >= 'a' && character <= 'z' ||
1711                    character >= 'A' && character <= 'Z')) {
1712                return false;
1713            }
1714        }
1715
1716        return true;
1717    }
1718
1719    /**
1720     * A UN M.49 is a 3 digit numeric code.
1721     */
1722    private static boolean isUnM49AreaCode(String code) {
1723        if (code.length() != 3) {
1724            return false;
1725        }
1726
1727        for (int i = 0; i < 3; ++i) {
1728            final char character = code.charAt(i);
1729            if (!(character >= '0' && character <= '9')) {
1730                return false;
1731            }
1732        }
1733
1734        return true;
1735    }
1736
1737    /**
1738     * Returns a name for the locale's variant code that is appropriate for display to the
1739     * user.  If possible, the name will be localized for the default locale.  If the locale
1740     * doesn't specify a variant code, this function returns the empty string.
1741     */
1742    public final String getDisplayVariant() {
1743        return getDisplayVariant(getDefault(Category.DISPLAY));
1744    }
1745
1746    /**
1747     * Returns the full variant name in the specified {@code Locale} for the variant code
1748     * of this {@code Locale}. If there is no matching variant name, the variant code is
1749     * returned.
1750     *
1751     * @since 1.7
1752     */
1753    public String getDisplayVariant(Locale locale) {
1754        String variantCode = baseLocale.getVariant();
1755        if (variantCode.isEmpty()) {
1756            return "";
1757        }
1758
1759        try {
1760            normalizeAndValidateVariant(variantCode);
1761        } catch (IllformedLocaleException ilfe) {
1762            return variantCode;
1763        }
1764
1765        String result = ICU.getDisplayVariant(this, locale);
1766        if (result == null) { // TODO: do we need to do this, or does ICU do it for us?
1767            result = ICU.getDisplayVariant(this, Locale.getDefault());
1768        }
1769
1770        // The "old style" locale constructors allow us to pass in variants that aren't
1771        // valid BCP-47 variant subtags. When that happens, toLanguageTag will not emit
1772        // them. Note that we know variantCode.length() > 0 due to the isEmpty check at
1773        // the beginning of this function.
1774        if (result.isEmpty()) {
1775            return variantCode;
1776        }
1777        return result;
1778    }
1779
1780    private static String normalizeAndValidateVariant(String variant) {
1781        if (variant == null || variant.isEmpty()) {
1782            return "";
1783        }
1784
1785        // Note that unlike extensions, we canonicalize to lower case alphabets
1786        // and underscores instead of hyphens.
1787        final String normalizedVariant = variant.replace('-', '_');
1788        String[] subTags = normalizedVariant.split("_");
1789
1790        for (String subTag : subTags) {
1791            if (!isValidVariantSubtag(subTag)) {
1792                throw new IllformedLocaleException("Invalid variant: " + variant);
1793            }
1794        }
1795
1796        return normalizedVariant;
1797    }
1798
1799    private static boolean isValidVariantSubtag(String subTag) {
1800        // The BCP-47 spec states that :
1801        // - Subtags can be between [5, 8] alphanumeric chars in length.
1802        // - Subtags that start with a number are allowed to be 4 chars in length.
1803        if (subTag.length() >= 5 && subTag.length() <= 8) {
1804            if (isAsciiAlphaNum(subTag)) {
1805                return true;
1806            }
1807        } else if (subTag.length() == 4) {
1808            final char firstChar = subTag.charAt(0);
1809            if ((firstChar >= '0' && firstChar <= '9') && isAsciiAlphaNum(subTag)) {
1810                return true;
1811            }
1812        }
1813
1814        return false;
1815    }
1816
1817    /**
1818     * Returns a name for the locale that is appropriate for display to the
1819     * user. This will be the values returned by getDisplayLanguage(),
1820     * getDisplayScript(), getDisplayCountry(), and getDisplayVariant() assembled
1821     * into a single string. The the non-empty values are used in order,
1822     * with the second and subsequent names in parentheses.  For example:
1823     * <blockquote>
1824     * language (script, country, variant)<br>
1825     * language (country)<br>
1826     * language (variant)<br>
1827     * script (country)<br>
1828     * country<br>
1829     * </blockquote>
1830     * depending on which fields are specified in the locale.  If the
1831     * language, sacript, country, and variant fields are all empty,
1832     * this function returns the empty string.
1833     */
1834    public final String getDisplayName() {
1835        return getDisplayName(getDefault(Category.DISPLAY));
1836    }
1837
1838    /**
1839     * Returns this locale's language name, country name, and variant, localized
1840     * to {@code locale}. The exact output form depends on whether this locale
1841     * corresponds to a specific language, script, country and variant.
1842     *
1843     * <p>For example:
1844     * <ul>
1845     * <li>{@code new Locale("en").getDisplayName(Locale.US)} -> {@code English}
1846     * <li>{@code new Locale("en", "US").getDisplayName(Locale.US)} -> {@code English (United States)}
1847     * <li>{@code new Locale("en", "US", "POSIX").getDisplayName(Locale.US)} -> {@code English (United States,Computer)}
1848     * <li>{@code Locale.fromLanguageTag("zh-Hant-CN").getDisplayName(Locale.US)} -> {@code Chinese (Traditional Han,China)}
1849     * <li>{@code new Locale("en").getDisplayName(Locale.FRANCE)} -> {@code anglais}
1850     * <li>{@code new Locale("en", "US").getDisplayName(Locale.FRANCE)} -> {@code anglais (États-Unis)}
1851     * <li>{@code new Locale("en", "US", "POSIX").getDisplayName(Locale.FRANCE)} -> {@code anglais (États-Unis,informatique)}.
1852     * </ul>
1853     */
1854    public String getDisplayName(Locale locale) {
1855        int count = 0;
1856        StringBuilder buffer = new StringBuilder();
1857        String languageCode = baseLocale.getLanguage();
1858        if (!languageCode.isEmpty()) {
1859            String displayLanguage = getDisplayLanguage(locale);
1860            buffer.append(displayLanguage.isEmpty() ? languageCode : displayLanguage);
1861            ++count;
1862        }
1863        String scriptCode = baseLocale.getScript();
1864        if (!scriptCode.isEmpty()) {
1865            if (count == 1) {
1866                buffer.append(" (");
1867            }
1868            String displayScript = getDisplayScript(locale);
1869            buffer.append(displayScript.isEmpty() ? scriptCode : displayScript);
1870            ++count;
1871        }
1872        String countryCode = baseLocale.getRegion();
1873        if (!countryCode.isEmpty()) {
1874            if (count == 1) {
1875                buffer.append(" (");
1876            } else if (count == 2) {
1877                buffer.append(",");
1878            }
1879            String displayCountry = getDisplayCountry(locale);
1880            buffer.append(displayCountry.isEmpty() ? countryCode : displayCountry);
1881            ++count;
1882        }
1883        String variantCode = baseLocale.getVariant();
1884        if (!variantCode.isEmpty()) {
1885            if (count == 1) {
1886                buffer.append(" (");
1887            } else if (count == 2 || count == 3) {
1888                buffer.append(",");
1889            }
1890            String displayVariant = getDisplayVariant(locale);
1891            buffer.append(displayVariant.isEmpty() ? variantCode : displayVariant);
1892            ++count;
1893        }
1894        if (count > 1) {
1895            buffer.append(")");
1896        }
1897        return buffer.toString();
1898    }
1899
1900    /**
1901     * Overrides Cloneable.
1902     */
1903    public Object clone()
1904    {
1905        try {
1906            Locale that = (Locale)super.clone();
1907            return that;
1908        } catch (CloneNotSupportedException e) {
1909            throw new InternalError();
1910        }
1911    }
1912
1913    /**
1914     * Override hashCode.
1915     * Since Locales are often used in hashtables, caches the value
1916     * for speed.
1917     */
1918    @Override
1919    public int hashCode() {
1920        int hc = hashCodeValue;
1921        if (hc == 0) {
1922            hc = baseLocale.hashCode();
1923            if (localeExtensions != null) {
1924                hc ^= localeExtensions.hashCode();
1925            }
1926            hashCodeValue = hc;
1927        }
1928        return hc;
1929    }
1930
1931    // Overrides
1932
1933    /**
1934     * Returns true if this Locale is equal to another object.  A Locale is
1935     * deemed equal to another Locale with identical language, script, country,
1936     * variant and extensions, and unequal to all other objects.
1937     *
1938     * @return true if this Locale is equal to the specified object.
1939     */
1940    @Override
1941    public boolean equals(Object obj) {
1942        if (this == obj)                      // quick check
1943            return true;
1944        if (!(obj instanceof Locale))
1945            return false;
1946        BaseLocale otherBase = ((Locale)obj).baseLocale;
1947        if (!baseLocale.equals(otherBase)) {
1948            return false;
1949        }
1950        if (localeExtensions == null) {
1951            return ((Locale)obj).localeExtensions == null;
1952        }
1953        return localeExtensions.equals(((Locale)obj).localeExtensions);
1954    }
1955
1956    // ================= privates =====================================
1957
1958    private transient BaseLocale baseLocale;
1959    private transient LocaleExtensions localeExtensions;
1960
1961    /**
1962     * Calculated hashcode
1963     */
1964    private transient volatile int hashCodeValue = 0;
1965
1966    private static Locale defaultLocale = null;
1967    private static Locale defaultDisplayLocale = null;
1968    private static Locale defaultFormatLocale = null;
1969
1970    /**
1971     * Format a list using given pattern strings.
1972     * If either of the patterns is null, then a the list is
1973     * formatted by concatenation with the delimiter ','.
1974     * @param stringList the list of strings to be formatted.
1975     * @param listPattern should create a MessageFormat taking 0-3 arguments
1976     * and formatting them into a list.
1977     * @param listCompositionPattern should take 2 arguments
1978     * and is used by composeList.
1979     * @return a string representing the list.
1980     */
1981    private static String formatList(String[] stringList, String listPattern, String listCompositionPattern) {
1982        // If we have no list patterns, compose the list in a simple,
1983        // non-localized way.
1984        if (listPattern == null || listCompositionPattern == null) {
1985            StringBuffer result = new StringBuffer();
1986            for (int i=0; i<stringList.length; ++i) {
1987                if (i>0) result.append(',');
1988                result.append(stringList[i]);
1989            }
1990            return result.toString();
1991        }
1992
1993        // Compose the list down to three elements if necessary
1994        if (stringList.length > 3) {
1995            MessageFormat format = new MessageFormat(listCompositionPattern);
1996            stringList = composeList(format, stringList);
1997        }
1998
1999        // Rebuild the argument list with the list length as the first element
2000        Object[] args = new Object[stringList.length + 1];
2001        System.arraycopy(stringList, 0, args, 1, stringList.length);
2002        args[0] = new Integer(stringList.length);
2003
2004        // Format it using the pattern in the resource
2005        MessageFormat format = new MessageFormat(listPattern);
2006        return format.format(args);
2007    }
2008
2009    /**
2010     * Given a list of strings, return a list shortened to three elements.
2011     * Shorten it by applying the given format to the first two elements
2012     * recursively.
2013     * @param format a format which takes two arguments
2014     * @param list a list of strings
2015     * @return if the list is three elements or shorter, the same list;
2016     * otherwise, a new list of three elements.
2017     */
2018    private static String[] composeList(MessageFormat format, String[] list) {
2019        if (list.length <= 3) return list;
2020
2021        // Use the given format to compose the first two elements into one
2022        String[] listItems = { list[0], list[1] };
2023        String newItem = format.format(listItems);
2024
2025        // Form a new list one element shorter
2026        String[] newList = new String[list.length-1];
2027        System.arraycopy(list, 2, newList, 1, newList.length-1);
2028        newList[0] = newItem;
2029
2030        // Recurse
2031        return composeList(format, newList);
2032    }
2033
2034    /**
2035     * @serialField language    String
2036     *      language subtag in lower case. (See <a href="java/util/Locale.html#getLanguage()">getLanguage()</a>)
2037     * @serialField country     String
2038     *      country subtag in upper case. (See <a href="java/util/Locale.html#getCountry()">getCountry()</a>)
2039     * @serialField variant     String
2040     *      variant subtags separated by LOWLINE characters. (See <a href="java/util/Locale.html#getVariant()">getVariant()</a>)
2041     * @serialField hashcode    int
2042     *      deprecated, for forward compatibility only
2043     * @serialField script      String
2044     *      script subtag in title case (See <a href="java/util/Locale.html#getScript()">getScript()</a>)
2045     * @serialField extensions  String
2046     *      canonical representation of extensions, that is,
2047     *      BCP47 extensions in alphabetical order followed by
2048     *      BCP47 private use subtags, all in lower case letters
2049     *      separated by HYPHEN-MINUS characters.
2050     *      (See <a href="java/util/Locale.html#getExtensionKeys()">getExtensionKeys()</a>,
2051     *      <a href="java/util/Locale.html#getExtension(char)">getExtension(char)</a>)
2052     */
2053    private static final ObjectStreamField[] serialPersistentFields = {
2054        new ObjectStreamField("language", String.class),
2055        new ObjectStreamField("country", String.class),
2056        new ObjectStreamField("variant", String.class),
2057        new ObjectStreamField("hashcode", int.class),
2058        new ObjectStreamField("script", String.class),
2059        new ObjectStreamField("extensions", String.class),
2060    };
2061
2062    /**
2063     * Serializes this <code>Locale</code> to the specified <code>ObjectOutputStream</code>.
2064     * @param out the <code>ObjectOutputStream</code> to write
2065     * @throws IOException
2066     * @since 1.7
2067     */
2068    private void writeObject(ObjectOutputStream out) throws IOException {
2069        ObjectOutputStream.PutField fields = out.putFields();
2070        fields.put("language", baseLocale.getLanguage());
2071        fields.put("script", baseLocale.getScript());
2072        fields.put("country", baseLocale.getRegion());
2073        fields.put("variant", baseLocale.getVariant());
2074        fields.put("extensions", localeExtensions == null ? "" : localeExtensions.getID());
2075        fields.put("hashcode", -1); // place holder just for backward support
2076        out.writeFields();
2077    }
2078
2079    /**
2080     * Deserializes this <code>Locale</code>.
2081     * @param in the <code>ObjectInputStream</code> to read
2082     * @throws IOException
2083     * @throws ClassNotFoundException
2084     * @throws IllformedLocaleException
2085     * @since 1.7
2086     */
2087    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
2088        ObjectInputStream.GetField fields = in.readFields();
2089        String language = (String)fields.get("language", "");
2090        String script = (String)fields.get("script", "");
2091        String country = (String)fields.get("country", "");
2092        String variant = (String)fields.get("variant", "");
2093        String extStr = (String)fields.get("extensions", "");
2094        baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), script, country, variant);
2095        if (extStr.length() > 0) {
2096            try {
2097                InternalLocaleBuilder bldr = new InternalLocaleBuilder();
2098                bldr.setExtensions(extStr);
2099                localeExtensions = bldr.getLocaleExtensions();
2100            } catch (LocaleSyntaxException e) {
2101                throw new IllformedLocaleException(e.getMessage());
2102            }
2103        } else {
2104            localeExtensions = null;
2105        }
2106    }
2107
2108    /**
2109     * Returns a cached <code>Locale</code> instance equivalent to
2110     * the deserialized <code>Locale</code>. When serialized
2111     * language, country and variant fields read from the object data stream
2112     * are exactly "ja", "JP", "JP" or "th", "TH", "TH" and script/extensions
2113     * fields are empty, this method supplies <code>UNICODE_LOCALE_EXTENSION</code>
2114     * "ca"/"japanese" (calendar type is "japanese") or "nu"/"thai" (number script
2115     * type is "thai"). See <a href="Locale.html#special_cases_constructor"/>Special Cases</a>
2116     * for more information.
2117     *
2118     * @return an instance of <code>Locale</code> equivalent to
2119     * the deserialized <code>Locale</code>.
2120     * @throws java.io.ObjectStreamException
2121     */
2122    private Object readResolve() throws java.io.ObjectStreamException {
2123        return getInstance(baseLocale.getLanguage(), baseLocale.getScript(),
2124                baseLocale.getRegion(), baseLocale.getVariant(), localeExtensions);
2125    }
2126
2127    private static volatile String[] isoLanguages = null;
2128
2129    private static volatile String[] isoCountries = null;
2130
2131    private static String convertOldISOCodes(String language) {
2132        // we accept both the old and the new ISO codes for the languages whose ISO
2133        // codes have changed, but we always store the OLD code, for backward compatibility
2134        language = LocaleUtils.toLowerString(language).intern();
2135        if (language == "he") {
2136            return "iw";
2137        } else if (language == "yi") {
2138            return "ji";
2139        } else if (language == "id") {
2140            return "in";
2141        } else {
2142            return language;
2143        }
2144    }
2145
2146    private static LocaleExtensions getCompatibilityExtensions(String language,
2147                                                               String script,
2148                                                               String country,
2149                                                               String variant) {
2150        LocaleExtensions extensions = null;
2151        // Special cases for backward compatibility support
2152        if (LocaleUtils.caseIgnoreMatch(language, "ja")
2153                && script.length() == 0
2154                && LocaleUtils.caseIgnoreMatch(country, "jp")
2155                && "JP".equals(variant)) {
2156            // ja_JP_JP -> u-ca-japanese (calendar = japanese)
2157            extensions = LocaleExtensions.CALENDAR_JAPANESE;
2158        } else if (LocaleUtils.caseIgnoreMatch(language, "th")
2159                && script.length() == 0
2160                && LocaleUtils.caseIgnoreMatch(country, "th")
2161                && "TH".equals(variant)) {
2162            // th_TH_TH -> u-nu-thai (numbersystem = thai)
2163            extensions = LocaleExtensions.NUMBER_THAI;
2164        }
2165        return extensions;
2166    }
2167
2168    /**
2169     * @hide for internal use only.
2170     */
2171    public static String adjustLanguageCode(String languageCode) {
2172        String adjusted = languageCode.toLowerCase(Locale.US);
2173        // Map new language codes to the obsolete language
2174        // codes so the correct resource bundles will be used.
2175        if (languageCode.equals("he")) {
2176            adjusted = "iw";
2177        } else if (languageCode.equals("id")) {
2178            adjusted = "in";
2179        } else if (languageCode.equals("yi")) {
2180            adjusted = "ji";
2181        }
2182
2183        return adjusted;
2184    }
2185
2186    /**
2187     * Enum for locale categories.  These locale categories are used to get/set
2188     * the default locale for the specific functionality represented by the
2189     * category.
2190     *
2191     * @see #getDefault(Locale.Category)
2192     * @see #setDefault(Locale.Category, Locale)
2193     * @since 1.7
2194     */
2195    public enum Category {
2196
2197        /**
2198         * Category used to represent the default locale for
2199         * displaying user interfaces.
2200         */
2201        DISPLAY("user.language.display",
2202                "user.script.display",
2203                "user.country.display",
2204                "user.variant.display"),
2205
2206        /**
2207         * Category used to represent the default locale for
2208         * formatting dates, numbers, and/or currencies.
2209         */
2210        FORMAT("user.language.format",
2211               "user.script.format",
2212               "user.country.format",
2213               "user.variant.format");
2214
2215        Category(String languageKey, String scriptKey, String countryKey, String variantKey) {
2216            this.languageKey = languageKey;
2217            this.scriptKey = scriptKey;
2218            this.countryKey = countryKey;
2219            this.variantKey = variantKey;
2220        }
2221
2222        final String languageKey;
2223        final String scriptKey;
2224        final String countryKey;
2225        final String variantKey;
2226    }
2227
2228    /**
2229     * <code>Builder</code> is used to build instances of <code>Locale</code>
2230     * from values configured by the setters.  Unlike the <code>Locale</code>
2231     * constructors, the <code>Builder</code> checks if a value configured by a
2232     * setter satisfies the syntax requirements defined by the <code>Locale</code>
2233     * class.  A <code>Locale</code> object created by a <code>Builder</code> is
2234     * well-formed and can be transformed to a well-formed IETF BCP 47 language tag
2235     * without losing information.
2236     *
2237     * <p><b>Note:</b> The <code>Locale</code> class does not provide any
2238     * syntactic restrictions on variant, while BCP 47 requires each variant
2239     * subtag to be 5 to 8 alphanumerics or a single numeric followed by 3
2240     * alphanumerics.  The method <code>setVariant</code> throws
2241     * <code>IllformedLocaleException</code> for a variant that does not satisfy
2242     * this restriction. If it is necessary to support such a variant, use a
2243     * Locale constructor.  However, keep in mind that a <code>Locale</code>
2244     * object created this way might lose the variant information when
2245     * transformed to a BCP 47 language tag.
2246     *
2247     * <p>The following example shows how to create a <code>Locale</code> object
2248     * with the <code>Builder</code>.
2249     * <blockquote>
2250     * <pre>
2251     *     Locale aLocale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build();
2252     * </pre>
2253     * </blockquote>
2254     *
2255     * <p>Builders can be reused; <code>clear()</code> resets all
2256     * fields to their default values.
2257     *
2258     * @see Locale#forLanguageTag
2259     * @since 1.7
2260     */
2261    public static final class Builder {
2262        private final InternalLocaleBuilder localeBuilder;
2263
2264        /**
2265         * Constructs an empty Builder. The default value of all
2266         * fields, extensions, and private use information is the
2267         * empty string.
2268         */
2269        public Builder() {
2270            localeBuilder = new InternalLocaleBuilder();
2271        }
2272
2273        /**
2274         * Resets the <code>Builder</code> to match the provided
2275         * <code>locale</code>.  Existing state is discarded.
2276         *
2277         * <p>All fields of the locale must be well-formed, see {@link Locale}.
2278         *
2279         * <p>Locales with any ill-formed fields cause
2280         * <code>IllformedLocaleException</code> to be thrown, except for the
2281         * following three cases which are accepted for compatibility
2282         * reasons:<ul>
2283         * <li>Locale("ja", "JP", "JP") is treated as "ja-JP-u-ca-japanese"
2284         * <li>Locale("th", "TH", "TH") is treated as "th-TH-u-nu-thai"
2285         * <li>Locale("no", "NO", "NY") is treated as "nn-NO"</ul>
2286         *
2287         * @param locale the locale
2288         * @return This builder.
2289         * @throws IllformedLocaleException if <code>locale</code> has
2290         * any ill-formed fields.
2291         * @throws NullPointerException if <code>locale</code> is null.
2292         */
2293        public Builder setLocale(Locale locale) {
2294            try {
2295                localeBuilder.setLocale(locale.baseLocale, locale.localeExtensions);
2296            } catch (LocaleSyntaxException e) {
2297                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2298            }
2299            return this;
2300        }
2301
2302        /**
2303         * Resets the Builder to match the provided IETF BCP 47
2304         * language tag.  Discards the existing state.  Null and the
2305         * empty string cause the builder to be reset, like {@link
2306         * #clear}.  Grandfathered tags (see {@link
2307         * Locale#forLanguageTag}) are converted to their canonical
2308         * form before being processed.  Otherwise, the language tag
2309         * must be well-formed (see {@link Locale}) or an exception is
2310         * thrown (unlike <code>Locale.forLanguageTag</code>, which
2311         * just discards ill-formed and following portions of the
2312         * tag).
2313         *
2314         * @param languageTag the language tag
2315         * @return This builder.
2316         * @throws IllformedLocaleException if <code>languageTag</code> is ill-formed
2317         * @see Locale#forLanguageTag(String)
2318         */
2319        public Builder setLanguageTag(String languageTag) {
2320            ParseStatus sts = new ParseStatus();
2321            LanguageTag tag = LanguageTag.parse(languageTag, sts);
2322            if (sts.isError()) {
2323                throw new IllformedLocaleException(sts.getErrorMessage(), sts.getErrorIndex());
2324            }
2325            localeBuilder.setLanguageTag(tag);
2326            return this;
2327        }
2328
2329        /**
2330         * Sets the language.  If <code>language</code> is the empty string or
2331         * null, the language in this <code>Builder</code> is removed.  Otherwise,
2332         * the language must be <a href="./Locale.html#def_language">well-formed</a>
2333         * or an exception is thrown.
2334         *
2335         * <p>The typical language value is a two or three-letter language
2336         * code as defined in ISO639.
2337         *
2338         * @param language the language
2339         * @return This builder.
2340         * @throws IllformedLocaleException if <code>language</code> is ill-formed
2341         */
2342        public Builder setLanguage(String language) {
2343            try {
2344                localeBuilder.setLanguage(language);
2345            } catch (LocaleSyntaxException e) {
2346                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2347            }
2348            return this;
2349        }
2350
2351        /**
2352         * Sets the script. If <code>script</code> is null or the empty string,
2353         * the script in this <code>Builder</code> is removed.
2354         * Otherwise, the script must be <a href="./Locale.html#def_script">well-formed</a> or an
2355         * exception is thrown.
2356         *
2357         * <p>The typical script value is a four-letter script code as defined by ISO 15924.
2358         *
2359         * @param script the script
2360         * @return This builder.
2361         * @throws IllformedLocaleException if <code>script</code> is ill-formed
2362         */
2363        public Builder setScript(String script) {
2364            try {
2365                localeBuilder.setScript(script);
2366            } catch (LocaleSyntaxException e) {
2367                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2368            }
2369            return this;
2370        }
2371
2372        /**
2373         * Sets the region.  If region is null or the empty string, the region
2374         * in this <code>Builder</code> is removed.  Otherwise,
2375         * the region must be <a href="./Locale.html#def_region">well-formed</a> or an
2376         * exception is thrown.
2377         *
2378         * <p>The typical region value is a two-letter ISO 3166 code or a
2379         * three-digit UN M.49 area code.
2380         *
2381         * <p>The country value in the <code>Locale</code> created by the
2382         * <code>Builder</code> is always normalized to upper case.
2383         *
2384         * @param region the region
2385         * @return This builder.
2386         * @throws IllformedLocaleException if <code>region</code> is ill-formed
2387         */
2388        public Builder setRegion(String region) {
2389            try {
2390                localeBuilder.setRegion(region);
2391            } catch (LocaleSyntaxException e) {
2392                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2393            }
2394            return this;
2395        }
2396
2397        /**
2398         * Sets the variant.  If variant is null or the empty string, the
2399         * variant in this <code>Builder</code> is removed.  Otherwise, it
2400         * must consist of one or more <a href="./Locale.html#def_variant">well-formed</a>
2401         * subtags, or an exception is thrown.
2402         *
2403         * <p><b>Note:</b> This method checks if <code>variant</code>
2404         * satisfies the IETF BCP 47 variant subtag's syntax requirements,
2405         * and normalizes the value to lowercase letters.  However,
2406         * the <code>Locale</code> class does not impose any syntactic
2407         * restriction on variant, and the variant value in
2408         * <code>Locale</code> is case sensitive.  To set such a variant,
2409         * use a Locale constructor.
2410         *
2411         * @param variant the variant
2412         * @return This builder.
2413         * @throws IllformedLocaleException if <code>variant</code> is ill-formed
2414         */
2415        public Builder setVariant(String variant) {
2416            try {
2417                localeBuilder.setVariant(variant);
2418            } catch (LocaleSyntaxException e) {
2419                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2420            }
2421            return this;
2422        }
2423
2424        /**
2425         * Sets the extension for the given key. If the value is null or the
2426         * empty string, the extension is removed.  Otherwise, the extension
2427         * must be <a href="./Locale.html#def_extensions">well-formed</a> or an exception
2428         * is thrown.
2429         *
2430         * <p><b>Note:</b> The key {@link Locale#UNICODE_LOCALE_EXTENSION
2431         * UNICODE_LOCALE_EXTENSION} ('u') is used for the Unicode locale extension.
2432         * Setting a value for this key replaces any existing Unicode locale key/type
2433         * pairs with those defined in the extension.
2434         *
2435         * <p><b>Note:</b> The key {@link Locale#PRIVATE_USE_EXTENSION
2436         * PRIVATE_USE_EXTENSION} ('x') is used for the private use code. To be
2437         * well-formed, the value for this key needs only to have subtags of one to
2438         * eight alphanumeric characters, not two to eight as in the general case.
2439         *
2440         * @param key the extension key
2441         * @param value the extension value
2442         * @return This builder.
2443         * @throws IllformedLocaleException if <code>key</code> is illegal
2444         * or <code>value</code> is ill-formed
2445         * @see #setUnicodeLocaleKeyword(String, String)
2446         */
2447        public Builder setExtension(char key, String value) {
2448            try {
2449                localeBuilder.setExtension(key, value);
2450            } catch (LocaleSyntaxException e) {
2451                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2452            }
2453            return this;
2454        }
2455
2456        /**
2457         * Sets the Unicode locale keyword type for the given key.  If the type
2458         * is null, the Unicode keyword is removed.  Otherwise, the key must be
2459         * non-null and both key and type must be <a
2460         * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
2461         * is thrown.
2462         *
2463         * <p>Keys and types are converted to lower case.
2464         *
2465         * <p><b>Note</b>:Setting the 'u' extension via {@link #setExtension}
2466         * replaces all Unicode locale keywords with those defined in the
2467         * extension.
2468         *
2469         * @param key the Unicode locale key
2470         * @param type the Unicode locale type
2471         * @return This builder.
2472         * @throws IllformedLocaleException if <code>key</code> or <code>type</code>
2473         * is ill-formed
2474         * @throws NullPointerException if <code>key</code> is null
2475         * @see #setExtension(char, String)
2476         */
2477        public Builder setUnicodeLocaleKeyword(String key, String type) {
2478            try {
2479                localeBuilder.setUnicodeLocaleKeyword(key, type);
2480            } catch (LocaleSyntaxException e) {
2481                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2482            }
2483            return this;
2484        }
2485
2486        /**
2487         * Adds a unicode locale attribute, if not already present, otherwise
2488         * has no effect.  The attribute must not be null and must be <a
2489         * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
2490         * is thrown.
2491         *
2492         * @param attribute the attribute
2493         * @return This builder.
2494         * @throws NullPointerException if <code>attribute</code> is null
2495         * @throws IllformedLocaleException if <code>attribute</code> is ill-formed
2496         * @see #setExtension(char, String)
2497         */
2498        public Builder addUnicodeLocaleAttribute(String attribute) {
2499            try {
2500                localeBuilder.addUnicodeLocaleAttribute(attribute);
2501            } catch (LocaleSyntaxException e) {
2502                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2503            }
2504            return this;
2505        }
2506
2507        /**
2508         * Removes a unicode locale attribute, if present, otherwise has no
2509         * effect.  The attribute must not be null and must be <a
2510         * href="./Locale.html#def_locale_extension">well-formed</a> or an exception
2511         * is thrown.
2512         *
2513         * <p>Attribute comparision for removal is case-insensitive.
2514         *
2515         * @param attribute the attribute
2516         * @return This builder.
2517         * @throws NullPointerException if <code>attribute</code> is null
2518         * @throws IllformedLocaleException if <code>attribute</code> is ill-formed
2519         * @see #setExtension(char, String)
2520         */
2521        public Builder removeUnicodeLocaleAttribute(String attribute) {
2522            try {
2523                localeBuilder.removeUnicodeLocaleAttribute(attribute);
2524            } catch (LocaleSyntaxException e) {
2525                throw new IllformedLocaleException(e.getMessage(), e.getErrorIndex());
2526            }
2527            return this;
2528        }
2529
2530        /**
2531         * Resets the builder to its initial, empty state.
2532         *
2533         * @return This builder.
2534         */
2535        public Builder clear() {
2536            localeBuilder.clear();
2537            return this;
2538        }
2539
2540        /**
2541         * Resets the extensions to their initial, empty state.
2542         * Language, script, region and variant are unchanged.
2543         *
2544         * @return This builder.
2545         * @see #setExtension(char, String)
2546         */
2547        public Builder clearExtensions() {
2548            localeBuilder.clearExtensions();
2549            return this;
2550        }
2551
2552        /**
2553         * Returns an instance of <code>Locale</code> created from the fields set
2554         * on this builder.
2555         *
2556         * <p>This applies the conversions listed in {@link Locale#forLanguageTag}
2557         * when constructing a Locale. (Grandfathered tags are handled in
2558         * {@link #setLanguageTag}.)
2559         *
2560         * @return A Locale.
2561         */
2562        public Locale build() {
2563            BaseLocale baseloc = localeBuilder.getBaseLocale();
2564            LocaleExtensions extensions = localeBuilder.getLocaleExtensions();
2565            if (extensions == null && baseloc.getVariant().length() > 0) {
2566                extensions = getCompatibilityExtensions(baseloc.getLanguage(), baseloc.getScript(),
2567                        baseloc.getRegion(), baseloc.getVariant());
2568            }
2569            return Locale.getInstance(baseloc, extensions);
2570        }
2571    }
2572}
2573