API java : RuleBasedCollator


java.text
Class RuleBasedCollator

java.lang.Object
  extended by java.text.Collator
      extended by java.text.RuleBasedCollator
All Implemented Interfaces:
Cloneable, Comparator<Object>

public class RuleBasedCollator
extends Collator

The RuleBasedCollator class is a concrete subclass of Collator that provides a simple, data-driven, table collator. With this class you can create a customized table-based Collator. RuleBasedCollator maps characters to sort keys.

RuleBasedCollator has the following restrictions for efficiency (other subclasses may be used for more complex languages) :

  1. If a special collation rule controlled by a <modifier> is specified it applies to the whole collator object.
  2. All non-mentioned characters are at the end of the collation order.

The collation table is composed of a list of collation rules, where each rule is of one of three forms:

  1. <modifier>
  2. <relation> <text-argument>
  3. <reset> <text-argument>
The definitions of the rule elements is as follows:
  • Text-Argument: A text-argument is any sequence of characters, excluding special characters (that is, common whitespace characters [0009-000D, 0020] and rule syntax characters [0021-002F, 003A-0040, 005B-0060, 007B-007E]). If those characters are desired, you can put them in single quotes (e.g. ampersand => '&'). Note that unquoted white space characters are ignored; e.g. b c is treated as bc.
  • Modifier: There are currently two modifiers that turn on special collation rules.
    • '@' : Turns on backwards sorting of accents (secondary differences), as in French.
    • '!' : Turns on Thai/Lao vowel-consonant swapping. If this rule is in force when a Thai vowel of the range \U0E40-\U0E44 precedes a Thai consonant of the range \U0E01-\U0E2E OR a Lao vowel of the range \U0EC0-\U0EC4 precedes a Lao consonant of the range \U0E81-\U0EAE then the vowel is placed after the consonant for collation purposes.

    '@' : Indicates that accents are sorted backwards, as in French.

  • Relation: The relations are the following:
    • '<' : Greater, as a letter difference (primary)
    • ';' : Greater, as an accent difference (secondary)
    • ',' : Greater, as a case difference (tertiary)
    • '=' : Equal
  • Reset: There is a single reset which is used primarily for contractions and expansions, but which can also be used to add a modification at the end of a set of rules.

    '&' : Indicates that the next rule follows the position to where the reset text-argument would be sorted.

This sounds more complicated than it is in practice. For example, the following are equivalent ways of expressing the same thing:

  1. a < b < c
  2. a < b & b < c
  3. a < c & a < b
Notice that the order is important, as the subsequent item goes immediately after the text-argument. The following are not equivalent:
  1. a < b & a < c
  2. a < c & a < b
Either the text-argument must already be present in the sequence, or some initial substring of the text-argument must be present. (e.g. "a < b & ae < e" is valid since "a" is present in the sequence before "ae" is reset). In this latter case, "ae" is not entered and treated as a single character; instead, "e" is sorted as if it were expanded to two characters: "a" followed by an "e". This difference appears in natural languages: in traditional Spanish "ch" is treated as though it contracts to a single character (expressed as "c < ch < d"), while in traditional German a-umlaut is treated as though it expanded to two characters (expressed as "a,A < b,B ... &ae;\u00e3&AE;\u00c3"). [\u00e3 and \u00c3 are, of course, the escape sequences for a-umlaut.]

Ignorable Characters

For ignorable characters, the first rule must start with a relation (the examples we have used above are really fragments; "a < b" really should be "< a < b"). If, however, the first relation is not "<", then all the all text-arguments up to the first "<" are ignorable. For example, ", - < a < b" makes "-" an ignorable character, as we saw earlier in the word "black-birds". In the samples for different languages, you see that most accents are ignorable.

Normalization and Accents

RuleBasedCollator automatically processes its rule table to include both pre-composed and combining-character versions of accented characters. Even if the provided rule string contains only base characters and separate combining accent characters, the pre-composed accented characters matching all canonical combinations of characters from the rule string will be entered in the table.

This allows you to use a RuleBasedCollator to compare accented strings even when the collator is set to NO_DECOMPOSITION. There are two caveats, however. First, if the strings to be collated contain combining sequences that may not be in canonical order, you should set the collator to CANONICAL_DECOMPOSITION or FULL_DECOMPOSITION to enable sorting of combining sequences. Second, if the strings contain characters with compatibility decompositions (such as full-width and half-width forms), you must use FULL_DECOMPOSITION, since the rule tables only include canonical mappings.

Errors

The following are errors:

  • A text-argument contains unquoted punctuation symbols (e.g. "a < b-c < d").
  • A relation or reset character not followed by a text-argument (e.g. "a < ,b").
  • A reset where the text-argument (or an initial substring of the text-argument) is not already in the sequence. (e.g. "a < b & e < f")
If you produce one of these errors, a RuleBasedCollator throws a ParseException.

Examples

Simple: "< a < b < c < d"

Norwegian: "< a,A< b,B< c,C< d,D< e,E< f,F< g,G< h,H< i,I< j,J < k,K< l,L< m,M< n,N< o,O< p,P< q,Q< r,R< s,S< t,T < u,U< v,V< w,W< x,X< y,Y< z,Z < \u00E5=a\u030A,\u00C5=A\u030A ;aa,AA< \u00E6,\u00C6< \u00F8,\u00D8"

Normally, to create a rule-based Collator object, you will use Collator's factory method getInstance. However, to create a rule-based Collator object with specialized rules tailored to your needs, you construct the RuleBasedCollator with the rules contained in a String object. For example:

  1. String Simple = "< a< b< c< d";
  2. RuleBasedCollator mySimple = new RuleBasedCollator(Simple);
Or:
  1. String Norwegian = "< a,A< b,B< c,C< d,D< e,E< f,F< g,G< h,H< i,I< j,J" +
  2. "< k,K< l,L< m,M< n,N< o,O< p,P< q,Q< r,R< s,S< t,T" +
  3. "< u,U< v,V< w,W< x,X< y,Y< z,Z" +
  4. "< &#92;u00E5=a&#92;u030A,&#92;u00C5=A&#92;u030A" +
  5. ";aa,AA< &#92;u00E6,&#92;u00C6< &#92;u00F8,&#92;u00D8";
  6. RuleBasedCollator myNorwegian = new RuleBasedCollator(Norwegian);

Combining Collators is as simple as concatenating strings. Here's an example that combines two Collators from two different locales:

  1. // Create an en_US Collator object
  2. Collator.getInstance(new Locale("en", "US", ""));
  3. // Create a da_DK Collator object
  4. Collator.getInstance(new Locale("da", "DK", ""));
  5. // Combine the two
  6. // First, get the collation rules from en_USCollator
  7. String en_USRules = en_USCollator.getRules();
  8. // Second, get the collation rules from da_DKCollator
  9. String da_DKRules = da_DKCollator.getRules();
  10. RuleBasedCollator newCollator =
  11. new RuleBasedCollator(en_USRules + da_DKRules);
  12. // newCollator has the combined rules

Another more interesting example would be to make changes on an existing table to create a new Collator object. For example, add "&C< ch, cH, Ch, CH" to the en_USCollator object to create your own:

  1. // Create a new Collator object with additional rules
  2. String addRules = "&C< ch, cH, Ch, CH";
  3. RuleBasedCollator myCollator =
  4. new RuleBasedCollator(en_USCollator + addRules);
  5. // myCollator contains the new rules

The following example demonstrates how to change the order of non-spacing accents,

  1. // old rule
  2. String oldRules = "=&#92;u0301;&#92;u0300;&#92;u0302;&#92;u0308" // main accents
  3. + ";&#92;u0327;&#92;u0303;&#92;u0304;&#92;u0305" // main accents
  4. + ";&#92;u0306;&#92;u0307;&#92;u0309;&#92;u030A" // main accents
  5. + ";&#92;u030B;&#92;u030C;&#92;u030D;&#92;u030E" // main accents
  6. + ";&#92;u030F;&#92;u0310;&#92;u0311;&#92;u0312" // main accents
  7. + "< a , A ; ae, AE ; &#92;u00e6 , &#92;u00c6"
  8. + "< b , B < c, C < e, E & C < d, D";
  9. // change the order of accent characters
  10. String addOn = "& &#92;u0300 ; &#92;u0308 ; &#92;u0302";
  11. RuleBasedCollator myCollator = new RuleBasedCollator(oldRules + addOn);

The last example shows how to put new primary ordering in before the default setting. For example, in Japanese Collator, you can either sort English characters before or after Japanese characters,

  1. // get en_US Collator rules
  2. RuleBasedCollator en_USCollator = (RuleBasedCollator)Collator.getInstance(Locale.US);
  3. // add a few Japanese character to sort before English characters
  4. // suppose the last character before the first base letter 'a' in
  5. // the English collation rule is &#92;u2212
  6. String jaString = "& &#92;u2212 < &#92;u3041, &#92;u3042 < &#92;u3043, &#92;u3044";
  7. RuleBasedCollator myJapaneseCollator = new
  8. RuleBasedCollator(en_USCollator.getRules() + jaString);

See Also:
Collator, CollationElementIterator

Field Summary
 
Fields inherited from class java.text.Collator
CANONICAL_DECOMPOSITION, FULL_DECOMPOSITION, IDENTICAL, NO_DECOMPOSITION, PRIMARY, SECONDARY, TERTIARY
 
Constructor Summary
RuleBasedCollator(String rules)
          RuleBasedCollator constructor.
 
Method Summary
 Object clone()
          Standard override; no change in semantics.
 int compare(String source, String target)
          Compares the character data stored in two different strings based on the collation rules.
 boolean equals(Object obj)
          Compares the equality of two collation objects.
 CollationElementIterator getCollationElementIterator(CharacterIterator source)
          Return a CollationElementIterator for the given String.
 CollationElementIterator getCollationElementIterator(String source)
          Return a CollationElementIterator for the given String.
 CollationKey getCollationKey(String source)
          Transforms the string into a series of characters that can be compared with CollationKey.compareTo.
 String getRules()
          Gets the table-based rules for the collation object.
 int hashCode()
          Generates the hash code for the table-based collation object
 
Methods inherited from class java.text.Collator
compare, equals, getAvailableLocales, getDecomposition, getInstance, getInstance, getStrength, setDecomposition, setStrength
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

RuleBasedCollator

public RuleBasedCollator(String rules)
                  throws ParseException
RuleBasedCollator constructor. This takes the table rules and builds a collation table out of them. Please see RuleBasedCollator class description for more details on the collation rule syntax.

Parameters:
rules - the collation rules to build the collation table from.
Throws:
ParseException - A format exception will be thrown if the build process of the rules fails. For example, build rule "a < ? < d" will cause the constructor to throw the ParseException because the '?' is not quoted.
See Also:
Locale
Method Detail

getRules

public String getRules()
Gets the table-based rules for the collation object.

Returns:
returns the collation rules that the table collation object was created from.

getCollationElementIterator

public CollationElementIterator getCollationElementIterator(String source)
Return a CollationElementIterator for the given String.

See Also:
CollationElementIterator

getCollationElementIterator

public CollationElementIterator getCollationElementIterator(CharacterIterator source)
Return a CollationElementIterator for the given String.

Since:
1.2
See Also:
CollationElementIterator

compare

public int compare(String source,
                   String target)
Compares the character data stored in two different strings based on the collation rules. Returns information about whether a string is less than, greater than or equal to another string in a language. This can be overriden in a subclass.

Specified by:
compare in class Collator
Parameters:
source - the source string.
target - the target string.
Returns:
Returns an integer value. Value is less than zero if source is less than target, value is zero if source and target are equal, value is greater than zero if source is greater than target.
See Also:
CollationKey, Collator.getCollationKey(java.lang.String)

getCollationKey

public CollationKey getCollationKey(String source)
Transforms the string into a series of characters that can be compared with CollationKey.compareTo. This overrides java.text.Collator.getCollationKey. It can be overriden in a subclass.

Specified by:
getCollationKey in class Collator
Parameters:
source - the string to be transformed into a collation key.
Returns:
the CollationKey for the given String based on this Collator's collation rules. If the source String is null, a null CollationKey is returned.
See Also:
CollationKey, Collator.compare(java.lang.String, java.lang.String)

clone

public Object clone()
Standard override; no change in semantics.

Overrides:
clone in class Collator
Returns:
a clone of this instance.
See Also:
Cloneable

equals

public boolean equals(Object obj)
Compares the equality of two collation objects.

Specified by:
equals in interface Comparator<Object>
Overrides:
equals in class Collator
Parameters:
obj - the table-based collation object to be compared with this.
Returns:
true if the current table-based collation object is the same as the table-based collation object obj; false otherwise.
See Also:
Object.hashCode(), Hashtable

hashCode

public int hashCode()
Generates the hash code for the table-based collation object

Specified by:
hashCode in class Collator
Returns:
a hash code value for this object.
See Also:
Object.equals(java.lang.Object), Hashtable

Ces informations proviennent du site de http://java.sun.com

Remarques

Contenu

Le contenu de cette page provient du site de Sun, et est généré depuis un cache sur l'infobrol après certains traitements automatisés. La présentation peut donc différer du document original, mais le contenu aussi. Vous pouvez utiliser ce bouton pour afficher la page originale du site de Sun :

Quels sont les motivations de cette démarche?

Maintenir les pages en cache sur différents sites peut offrir plus de disponibilité.

Chaque page est indexée dans la base de donnée, ce qui permet de retrouver facilement les informations, au moyen des sommaires, du moteur de recherche interne, etc.

Des facilités sont mises en place pour que les membres de l'infobrol puissent effectuer des traductions en français des différents documents. Ceci devrait permettre aux débutants en programmation Java de consulter les API en français s'ils maîtrisent moins bien la langue de Shakespeare. Dans le cas où une traduction a été soumise, elle est disponible au moyen d'un lien en bas de page. Si la traduction a été validée, la page s'affiche par défaut en français, et un lien en bas de page permet d'atteindre la version en anglais.

Le code sur l'infobrol est automatiquement coloré selon la syntaxe, et les différents mots clés sont transformés en liens pour accéder rapidement aux informations.

Vous avez la possibilité de partager vos expériences en proposant vos propres extraits de code en utilisant le bouton "ajouter un commentaire" en bas de page. Si vous visitez simplement l'infobrol, vous avez déjà accès à cette fonction, mais si vous étes membre du brol, vous pouvez en plus utiliser des boutons supplémentaires de mise en forme, dont la coloration automatique de vos extraits de codes.

Réseaux sociaux

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher les interactions avec les réseaux sociaux sur ces pages.

 

Nuage de mots clés

7 mots clés dont 0 définis manuellement (plus d'information...).

Avertissement

Cette page ne possède pas encore de mots clés manuels, ceci est donc un exemple automatique (les niveaux de pertinence sont fictifs, mais les liens sont valables). Pour tester le nuage avec une page qui contient des mots définis manuellement, vous pouvez cliquer ici.

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher le nuage de mots clés.

 

Astuce pour imprimer les couleurs des cellules de tableaux : http://www.gaudry.be/ast-rf-450.html
Aucun commentaire pour cette page

© Ce document issu de l′infobrol est enregistré sous le certificat Cyber PrInterDeposit Digital Numbertection. Enregistrement IDDN n° 5329-695
Document créé le 21/07/06 14:13, dernière modification le Vendredi 17 Juin 2011, 12:12
Source du document imprimé : http://www.gaudry.be/java-api-rf-java/text/RuleBasedCollator.html Document affiché 2 fois ce mois de Juin.
St.Gaudry©07.01.02
Outils (masquer)
||
Recherche (afficher)
Recherche :

Utilisateur (masquer)
Apparence (afficher)
Stats (afficher)
15832 documents
452 astuces.
549 niouzes.
3099 definitions.
447 membres.
8115 messages.

Document genere en :
1,41 seconde

Mises à jour :
Mises à jour du site
Citation (masquer)
Le seul mauvais choix est l’absence de choix.

Amélie Nothomb
 
l'infobrol
Nous sommes le Vendredi 01 Juin 2012, 19:48, toutes les heures sont au format GMT+1.00 Heure, heure d'été (+1)