我想要实现的是通过字符串值对对象的集合进行排序.但是,使用collator以依赖于语言环境的方式.由于性能原因,我不想使用Collator compare()方法(如下面的代码中)而不是CollationKey类,因为java API声明使用CollationKey要快得多.
但是如何使用CollationKey实现compareTo()方法?据我所知,如果我将使用CollationKey,我必须自己完全编写所有的比较方法.所以我甚至不再能够使用Collections.sort()方法......我非常感谢一个易于理解的示例,以及使用CollationKey对Person对象的Collection进行排序的最有效实现.
谢谢!
public class Person implements Comparable<Person> {
String lastname;
public int compareTo(Person person) {
//This works but it is not the best implementation for a good performance
Collator instance = Collator.getInstance(Locale.ITALY);
return instance.compare(lastname, person.lastname);
}
}
...
ArrayList list = new ArrayList();
Person person1 = new Person("foo");
list.add(person1);
Person person2 = new Person("bar");
list.add(person2);
Collections.sort(list);
...
Run Code Online (Sandbox Code Playgroud)
eri*_*son 13
class Person implements Comparable<Person> {
private static final Collator collator = Collator.getInstance(Locale.ITALY);
private final String lastname;
private final CollationKey key;
Person(String lastname) {
this.lastname = lastname;
this.key = collator.getCollationKey(lastname);
}
public int compareTo(Person person) {
return key.compareTo(person.key);
}
}
Run Code Online (Sandbox Code Playgroud)