下面列出了java.text.Collator#setStrength ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* @tests java.text.Collator#setDecomposition(int)
*/
//FIXME This test fails on Harmony ClassLibrary
public void failing_test_setDecompositionI() {
Collator c = Collator.getInstance(Locale.FRENCH);
c.setStrength(Collator.IDENTICAL);
c.setDecomposition(Collator.NO_DECOMPOSITION);
assertTrue("Collator should not be using decomposition", !c.equals(
"\u212B", "\u00C5")); // "ANGSTROM SIGN" and "LATIN CAPITAL
// LETTER A WITH RING ABOVE"
c.setDecomposition(Collator.CANONICAL_DECOMPOSITION);
assertTrue("Collator should be using decomposition", c.equals("\u212B",
"\u00C5")); // "ANGSTROM SIGN" and "LATIN CAPITAL LETTER A WITH
// RING ABOVE"
assertTrue("Should not be equal under canonical decomposition", !c
.equals("\u2163", "IV")); // roman number "IV"
c.setDecomposition(Collator.FULL_DECOMPOSITION);
assertTrue("Should be equal under full decomposition", c.equals(
"\u2163", "IV")); // roman number "IV"
}
@Override
Comparator getComparator(final Context context) {
final Collator collator = Collator.getInstance(Locale.getDefault());
collator.setStrength(Collator.SECONDARY); // Case insensitive, process accents etc
return new Comparator() {
@Override
public int compare(Object o1, Object o2) {
EntityAccount a1 = (EntityAccount) o1;
EntityAccount a2 = (EntityAccount) o2;
int o = Integer.compare(
a1.order == null ? -1 : a1.order,
a2.order == null ? -1 : a2.order);
if (o != 0)
return o;
String name1 = (a1.name == null ? "" : a1.name);
String name2 = (a2.name == null ? "" : a2.name);
return collator.compare(name1, name2);
}
};
}
/**
* Compares the name of page 'a' to that of page 'b' with respect to the current locale (different languages have different alphabets and hence different orders).
*
*/
@Override
public int compare(final WikiPage a, final WikiPage b) {
// Be aware of locale when ordering
final I18nManager mgr = I18nManager.getInstance();
final Locale userLocale = mgr.getCurrentThreadLocale();
final Collator collator = Collator.getInstance(userLocale);
collator.setStrength(Collator.PRIMARY);
// Undefinied order if page a or b is null
int order = 0;
if (a != null && b != null) {
final String nameA = a.getPageName();
final String nameB = b.getPageName();
// Compare page names with the localized comparator
order = collator.compare(nameA, nameB);
}
return order;
}
/**
* Compares the name of page 'a' to that of page 'b' with respect to the current locale (different languages have different alphabets and hence different orders).
*
*/
@Override
public int compare(final WikiPage a, final WikiPage b) {
// Be aware of locale when ordering
final I18nManager mgr = I18nManager.getInstance();
final Locale userLocale = mgr.getCurrentThreadLocale();
final Collator collator = Collator.getInstance(userLocale);
collator.setStrength(Collator.PRIMARY);
// Undefinied order if page a or b is null
int order = 0;
if (a != null && b != null) {
final String nameA = a.getPageName();
final String nameB = b.getPageName();
// Compare page names with the localized comparator
order = collator.compare(nameA, nameB);
}
return order;
}
private void prepareListData() {
listDataHeader = new ArrayList<>();
listDataChild = new HashMap<>();
Collections.addAll(listDataHeader, getResources().getStringArray(R.array.breeds_array));
final String[] fileNames = getResources().getStringArray(R.array.file_names);
// load file names
for (int i = 0; i < listDataHeader.size(); i++) {
listDataChild.put(listDataHeader.get(i), fileNames[i]);
}
if (null != recogs) {
listDataHeader = new ArrayList<>();
listDataHeader.addAll(recogs);
expListView.setFastScrollAlwaysVisible(false);
} else {
final Collator coll = Collator.getInstance(Locale.getDefault());
coll.setStrength(Collator.PRIMARY);
Collections.sort(listDataHeader, coll);
expListView.setFastScrollAlwaysVisible(true);
}
}
/** @return The list of supported countries sorted by their localized display names. */
public static List<DropdownKeyValue> getSupportedCountries() {
List<String> countryCodes = new ArrayList<>();
List<String> countryNames = new ArrayList<>();
List<DropdownKeyValue> countries = new ArrayList<>();
nativeGetSupportedCountries(countryCodes, countryNames);
for (int i = 0; i < countryCodes.size(); i++) {
countries.add(new DropdownKeyValue(countryCodes.get(i), countryNames.get(i)));
}
final Collator collator = Collator.getInstance(Locale.getDefault());
collator.setStrength(Collator.PRIMARY);
Collections.sort(countries, new Comparator<DropdownKeyValue>() {
@Override
public int compare(DropdownKeyValue lhs, DropdownKeyValue rhs) {
int result = collator.compare(lhs.getValue(), rhs.getValue());
if (result == 0) result = lhs.getKey().compareTo(rhs.getKey());
return result;
}
});
return countries;
}
/**
* @tests java.text.Collator#equals(java.lang.Object)
*/
public void test_equalsLjava_lang_Object() {
Collator c = Collator.getInstance(Locale.ENGLISH);
Collator c2 = (Collator) c.clone();
assertTrue("Cloned collators not equal", c.equals(c2));
c2.setStrength(Collator.SECONDARY);
assertTrue("Collators with different strengths equal", !c.equals(c2));
}
/**
* ECMA 15.5.4.9 String.prototype.localeCompare (that)
* @param self self reference
* @param that comparison object
* @return result of locale sensitive comparison operation between {@code self} and {@code that}
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double localeCompare(final Object self, final Object that) {
final String str = checkObjectToString(self);
final Collator collator = Collator.getInstance(Global.getEnv()._locale);
collator.setStrength(Collator.IDENTICAL);
collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION);
return collator.compare(str, JSType.toString(that));
}
public void test_collationKeySize() throws Exception {
// Test to verify that very large collation keys are not truncated.
StringBuilder b = new StringBuilder();
for (int i = 0; i < 1024; i++) {
b.append("0123456789ABCDEF");
}
String sixteen = b.toString();
b.append("_THE_END");
String sixteenplus = b.toString();
Collator mColl = Collator.getInstance();
mColl.setStrength(Collator.PRIMARY);
byte [] arr = mColl.getCollationKey(sixteen).toByteArray();
int len = arr.length;
assertTrue("Collation key not 0 terminated", arr[arr.length - 1] == 0);
len--;
String foo = new String(arr, 0, len, "iso8859-1");
arr = mColl.getCollationKey(sixteen).toByteArray();
len = arr.length;
assertTrue("Collation key not 0 terminated", arr[arr.length - 1] == 0);
len--;
String bar = new String(arr, 0, len, "iso8859-1");
assertTrue("Collation keys should differ", foo.equals(bar));
}
/**
* ECMA 15.5.4.9 String.prototype.localeCompare (that)
* @param self self reference
* @param that comparison object
* @return result of locale sensitive comparison operation between {@code self} and {@code that}
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double localeCompare(final Object self, final Object that) {
final String str = checkObjectToString(self);
final Collator collator = Collator.getInstance(Global.getEnv()._locale);
collator.setStrength(Collator.IDENTICAL);
collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION);
return collator.compare(str, JSType.toString(that));
}
/**
* This doesn't output the string, but actually the collator byte stream
* which should be used as the uniqueness key. See ForBenefitOfUtilTest for examples
* of things that should or should not match each other.
*/
public static ByteString normalize(String input)
{
String n1 = Normalizer.normalize(input, Normalizer.Form.NFC);
// Not trying to be US-English centric, but have to pick some Locale
// so that this section will behave consistently for all nodes
Collator collator = Collator.getInstance(Locale.US);
collator.setStrength(Collator.PRIMARY);
collator.setDecomposition(Collator.FULL_DECOMPOSITION);
return ByteString.copyFrom(collator.getCollationKey(n1).toByteArray());
}
/**
* ECMA 15.5.4.9 String.prototype.localeCompare (that)
* @param self self reference
* @param that comparison object
* @return result of locale sensitive comparison operation between {@code self} and {@code that}
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object localeCompare(final Object self, final Object that) {
final String str = checkObjectToString(self);
final Collator collator = Collator.getInstance(Global.getEnv()._locale);
collator.setStrength(Collator.IDENTICAL);
collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION);
return (double)collator.compare(str, JSType.toString(that));
}
public void testThreadSafe() throws Exception {
int iters = 20 * RANDOM_MULTIPLIER;
for (int i = 0; i < iters; i++) {
Collator collator = Collator.getInstance(Locale.GERMAN);
collator.setStrength(Collator.PRIMARY);
Analyzer analyzer = new CollationKeyAnalyzer(collator);
assertThreadSafe(analyzer);
analyzer.close();
}
}
public final void TestProperty( )
{
Collator col = null;
try {
col = Collator.getInstance(Locale.ROOT);
logln("The property tests begin : ");
logln("Test ctors : ");
doAssert(col.compare("ab", "abc") < 0, "ab < abc comparison failed");
doAssert(col.compare("ab", "AB") < 0, "ab < AB comparison failed");
doAssert(col.compare("black-bird", "blackbird") > 0, "black-bird > blackbird comparison failed");
doAssert(col.compare("black bird", "black-bird") < 0, "black bird < black-bird comparison failed");
doAssert(col.compare("Hello", "hello") > 0, "Hello > hello comparison failed");
logln("Test ctors ends.");
logln("testing Collator.getStrength() method ...");
doAssert(col.getStrength() == Collator.TERTIARY, "collation object has the wrong strength");
doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference");
logln("testing Collator.setStrength() method ...");
col.setStrength(Collator.SECONDARY);
doAssert(col.getStrength() != Collator.TERTIARY, "collation object's strength is secondary difference");
doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference");
doAssert(col.getStrength() == Collator.SECONDARY, "collation object has the wrong strength");
logln("testing Collator.setDecomposition() method ...");
col.setDecomposition(Collator.NO_DECOMPOSITION);
doAssert(col.getDecomposition() != Collator.FULL_DECOMPOSITION, "collation object's strength is secondary difference");
doAssert(col.getDecomposition() != Collator.CANONICAL_DECOMPOSITION, "collation object's strength is primary difference");
doAssert(col.getDecomposition() == Collator.NO_DECOMPOSITION, "collation object has the wrong strength");
} catch (Exception foo) {
errln("Error : " + foo.getMessage());
errln("Default Collator creation failed.");
}
logln("Default collation property test ended.");
logln("Collator.getRules() testing ...");
doAssert(((RuleBasedCollator)col).getRules().length() != 0, "getRules() result incorrect" );
logln("getRules tests end.");
try {
col = Collator.getInstance(Locale.FRENCH);
col.setStrength(Collator.PRIMARY);
logln("testing Collator.getStrength() method again ...");
doAssert(col.getStrength() != Collator.TERTIARY, "collation object has the wrong strength");
doAssert(col.getStrength() == Collator.PRIMARY, "collation object's strength is not primary difference");
logln("testing French Collator.setStrength() method ...");
col.setStrength(Collator.TERTIARY);
doAssert(col.getStrength() == Collator.TERTIARY, "collation object's strength is not tertiary difference");
doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference");
doAssert(col.getStrength() != Collator.SECONDARY, "collation object's strength is secondary difference");
} catch (Exception bar) {
errln("Error : " + bar.getMessage());
errln("Creating French collation failed.");
}
logln("Create junk collation: ");
Locale abcd = new Locale("ab", "CD", "");
Collator junk = null;
try {
junk = Collator.getInstance(abcd);
} catch (Exception err) {
errln("Error : " + err.getMessage());
errln("Junk collation creation failed, should at least return the collator for the base bundle.");
}
try {
col = Collator.getInstance(Locale.ROOT);
doAssert(col.equals(junk), "The base bundle's collation should be returned.");
} catch (Exception exc) {
errln("Error : " + exc.getMessage());
errln("Default collation comparison, caching not working.");
}
logln("Collator property test ended.");
}
/**
* @tests java.text.Collator#compare(java.lang.Object, java.lang.Object)
*/
public void test_compareLjava_lang_ObjectLjava_lang_Object() {
Collator c = Collator.getInstance(Locale.FRENCH);
Object o, o2;
c.setStrength(Collator.IDENTICAL);
o = "E";
o2 = "F";
assertTrue("a) Failed on primary difference", c.compare(o, o2) < 0);
o = "e";
o2 = "\u00e9";
assertTrue("a) Failed on secondary difference", c.compare(o, o2) < 0);
o = "e";
o2 = "E";
assertTrue("a) Failed on tertiary difference", c.compare(o, o2) < 0);
o = "e";
o2 = "e";
assertEquals("a) Failed on equivalence", 0, c.compare(o, o2));
assertTrue("a) Failed on primary expansion",
c.compare("\u01db", "v") < 0);
c.setStrength(Collator.TERTIARY);
o = "E";
o2 = "F";
assertTrue("b) Failed on primary difference", c.compare(o, o2) < 0);
o = "e";
o2 = "\u00e9";
assertTrue("b) Failed on secondary difference", c.compare(o, o2) < 0);
o = "e";
o2 = "E";
assertTrue("b) Failed on tertiary difference", c.compare(o, o2) < 0);
o = "\u0001";
o2 = "\u0002";
assertEquals("b) Failed on identical", 0, c.compare(o, o2));
o = "e";
o2 = "e";
assertEquals("b) Failed on equivalence", 0, c.compare(o, o2));
c.setStrength(Collator.SECONDARY);
o = "E";
o2 = "F";
assertTrue("c) Failed on primary difference", c.compare(o, o2) < 0);
o = "e";
o2 = "\u00e9";
assertTrue("c) Failed on secondary difference", c.compare(o, o2) < 0);
o = "e";
o2 = "E";
assertEquals("c) Failed on tertiary difference", 0, c.compare(o, o2));
o = "\u0001";
o2 = "\u0002";
assertEquals("c) Failed on identical", 0, c.compare(o, o2));
o = "e";
o2 = "e";
assertEquals("c) Failed on equivalence", 0, c.compare(o, o2));
c.setStrength(Collator.PRIMARY);
o = "E";
o2 = "F";
assertTrue("d) Failed on primary difference", c.compare(o, o2) < 0);
o = "e";
o2 = "\u00e9";
assertEquals("d) Failed on secondary difference", 0, c.compare(o, o2));
o = "e";
o2 = "E";
assertEquals("d) Failed on tertiary difference", 0, c.compare(o, o2));
o = "\u0001";
o2 = "\u0002";
assertEquals("d) Failed on identical", 0, c.compare(o, o2));
o = "e";
o2 = "e";
assertEquals("d) Failed on equivalence", 0, c.compare(o, o2));
try {
c.compare("e", new StringBuffer("Blah"));
} catch (ClassCastException e) {
// correct
return;
}
fail("Failed to throw ClassCastException");
}
@Override
Comparator getComparator(final Context context) {
final Collator collator = Collator.getInstance(Locale.getDefault());
collator.setStrength(Collator.SECONDARY); // Case insensitive, process accents etc
final Comparator base = super.getComparator(context);
return new Comparator() {
@Override
public int compare(Object o1, Object o2) {
TupleFolderNav f1 = (TupleFolderNav) o1;
TupleFolderNav f2 = (TupleFolderNav) o2;
// Outbox
if (f1.accountName == null && f2.accountName == null)
return 0;
else if (f1.accountName == null)
return 1;
else if (f2.accountName == null)
return -1;
int fo = Integer.compare(
f1.order == null ? -1 : f1.order,
f2.order == null ? -1 : f2.order);
if (fo != 0)
return fo;
int ao = Integer.compare(
f1.accountOrder == null ? -1 : f1.accountOrder,
f2.accountOrder == null ? -1 : f2.accountOrder);
if (ao != 0)
return ao;
int a = collator.compare(f1.accountName, f2.accountName);
if (a != 0)
return a;
return base.compare(o1, o2);
}
};
}
@Override
Comparator getComparator(final Context context) {
final Collator collator = Collator.getInstance(Locale.getDefault());
collator.setStrength(Collator.SECONDARY); // Case insensitive, process accents etc
final Comparator base = super.getComparator(context);
return new Comparator() {
@Override
public int compare(Object o1, Object o2) {
TupleFolderEx f1 = (TupleFolderEx) o1;
TupleFolderEx f2 = (TupleFolderEx) o2;
// Outbox
if (f1.accountName == null && f2.accountName == null)
return 0;
else if (f1.accountName == null)
return 1;
else if (f2.accountName == null)
return -1;
int fo = Integer.compare(
f1.order == null ? -1 : f1.order,
f2.order == null ? -1 : f2.order);
if (fo != 0)
return fo;
int ao = Integer.compare(
f1.accountOrder == null ? -1 : f1.accountOrder,
f2.accountOrder == null ? -1 : f2.accountOrder);
if (ao != 0)
return ao;
int a = collator.compare(f1.accountName, f2.accountName);
if (a != 0)
return a;
return base.compare(o1, o2);
}
};
}
public int compare(OCFile o1, OCFile o2){
String s1 = o1.getRemotePath().toLowerCase();
String s2 = o2.getRemotePath().toLowerCase();
int thisMarker = 0;
int thatMarker = 0;
int s1Length = s1.length();
int s2Length = s2.length();
while (thisMarker < s1Length && thatMarker < s2Length) {
String thisChunk = getChunk(s1, s1Length, thisMarker);
thisMarker += thisChunk.length();
String thatChunk = getChunk(s2, s2Length, thatMarker);
thatMarker += thatChunk.length();
// If both chunks contain numeric characters, sort them numerically
int result = 0;
if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) {
// Simple chunk comparison by length.
int thisChunkLength = thisChunk.length();
result = thisChunkLength - thatChunk.length();
// If equal, the first different number counts
if (result == 0) {
for (int i = 0; i < thisChunkLength; i++) {
result = thisChunk.charAt(i) - thatChunk.charAt(i);
if (result != 0) {
return result;
}
}
}
} else {
Collator collator = Collator.getInstance();
collator.setStrength(Collator.PRIMARY);
result = collator.compare(thisChunk, thatChunk);
}
if (result != 0)
return result;
}
return s1Length - s2Length;
}
public final void TestProperty( )
{
Collator col = null;
try {
col = Collator.getInstance(Locale.ROOT);
logln("The property tests begin : ");
logln("Test ctors : ");
doAssert(col.compare("ab", "abc") < 0, "ab < abc comparison failed");
doAssert(col.compare("ab", "AB") < 0, "ab < AB comparison failed");
doAssert(col.compare("black-bird", "blackbird") > 0, "black-bird > blackbird comparison failed");
doAssert(col.compare("black bird", "black-bird") < 0, "black bird < black-bird comparison failed");
doAssert(col.compare("Hello", "hello") > 0, "Hello > hello comparison failed");
logln("Test ctors ends.");
logln("testing Collator.getStrength() method ...");
doAssert(col.getStrength() == Collator.TERTIARY, "collation object has the wrong strength");
doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference");
logln("testing Collator.setStrength() method ...");
col.setStrength(Collator.SECONDARY);
doAssert(col.getStrength() != Collator.TERTIARY, "collation object's strength is secondary difference");
doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference");
doAssert(col.getStrength() == Collator.SECONDARY, "collation object has the wrong strength");
logln("testing Collator.setDecomposition() method ...");
col.setDecomposition(Collator.NO_DECOMPOSITION);
doAssert(col.getDecomposition() != Collator.FULL_DECOMPOSITION, "collation object's strength is secondary difference");
doAssert(col.getDecomposition() != Collator.CANONICAL_DECOMPOSITION, "collation object's strength is primary difference");
doAssert(col.getDecomposition() == Collator.NO_DECOMPOSITION, "collation object has the wrong strength");
} catch (Exception foo) {
errln("Error : " + foo.getMessage());
errln("Default Collator creation failed.");
}
logln("Default collation property test ended.");
logln("Collator.getRules() testing ...");
doAssert(((RuleBasedCollator)col).getRules().length() != 0, "getRules() result incorrect" );
logln("getRules tests end.");
try {
col = Collator.getInstance(Locale.FRENCH);
col.setStrength(Collator.PRIMARY);
logln("testing Collator.getStrength() method again ...");
doAssert(col.getStrength() != Collator.TERTIARY, "collation object has the wrong strength");
doAssert(col.getStrength() == Collator.PRIMARY, "collation object's strength is not primary difference");
logln("testing French Collator.setStrength() method ...");
col.setStrength(Collator.TERTIARY);
doAssert(col.getStrength() == Collator.TERTIARY, "collation object's strength is not tertiary difference");
doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference");
doAssert(col.getStrength() != Collator.SECONDARY, "collation object's strength is secondary difference");
} catch (Exception bar) {
errln("Error : " + bar.getMessage());
errln("Creating French collation failed.");
}
logln("Create junk collation: ");
Locale abcd = new Locale("ab", "CD", "");
Collator junk = null;
try {
junk = Collator.getInstance(abcd);
} catch (Exception err) {
errln("Error : " + err.getMessage());
errln("Junk collation creation failed, should at least return the collator for the base bundle.");
}
try {
col = Collator.getInstance(Locale.ROOT);
doAssert(col.equals(junk), "The base bundle's collation should be returned.");
} catch (Exception exc) {
errln("Error : " + exc.getMessage());
errln("Default collation comparison, caching not working.");
}
logln("Collator property test ended.");
}
@Override
public int compareTo(@NotNull TwigPath twigPath) {
Collator collator = Collator.getInstance();
collator.setStrength(Collator.SECONDARY);
return collator.compare(this.getNamespace(), twigPath.getNamespace());
}