treeMap that uses a CollationKey to map to the original string. CollationKey implements the
interface Comparable with a compareTo method that can be much more efficient than using
Collator.compare.
class CollationKeySorting {
private TreeMap<CollationKey, String> sortedStrings;
private Collator collator;
CollationKeySorting(Collator collator) {
this.collator = collator;
sortedStrings = new TreeMap<CollationKey, String>();
}
void add(String str) {
sortedStrings.put(
collator.getCollationKey(str), str);
}
Iterator
return sortedStrings.values().iterator();
}
}
24.6.2. Formatting and Parsing
The abstract Format class provides methods to format and parse objects according to a locale. Format
declares a format method that takes an object and returns a formatted String, tHRowing
IllegalArgumentException if the object is not of a type known to the formatting object. Format also
declares a parseObject method that takes a String and returns an object initialized from the parsed data,
throwing ParseException if the string is not understood. Each of these methods is implemented as
appropriate for the particular kind of formatting. The package java.text provides three Format
subclasses:
- DateFormat was discussed in the previous section.
MessageFormat helps you localize output when printing messages that contain values from your
program. Because word order varies among languages, you cannot simply use a localized string
concatenated with your program's values. For example, the English phrase "a fantastic menu" would
in French have the word order "un menu fantastique." A message that took adjectives and nouns from
lists and displayed them in such a phrase could use a MessageFormat object to localize the order.
•
NumberFormat is an abstract class that defines a general way to format and parse various kinds of
numbers for different locales. It has two subclasses: ChoiceFormat to choose among alternatives
based on number (such as picking between a singular or plural variant of a word); and
DecimalFormat to format and parse decimal numbers. (The formatting capabilities of
NumberFormat are more powerful than those provided by java.util.Formatter.)
•
NumberFormat in turn has four different kinds of "get instance" methods. Each method uses either a
provided Locale object or the default locale.
getNumberInstance returns a general number formatter/parser. This is the kind of object
returned by the generic getInstance method.
•
getIntegerInstance returns a number formatter/parser that rounds floating-point values to the
nearest integer.
•
getCurrencyInstance returns a formatter/parser for currency values. The Currency object
used by a NumberFormatter can also be retrieved with the getCurrency method.
•
- getPercentInstance returns a formatter/parser for percentages.