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