题
我想要实现的排序于独创的建筑风格的对象一串的价值。然而在一个区域受扶养的方式利用一整理器.由于业绩原因,我不想使用的整理器比较()方法(如以下的代码),而CollationKey类,作为API国家的使用CollationKey的速度要快得多。
但我如何实施compareTo()方法使用CollationKey?据我理解它,我必须完全写在所有的比较方法我自己,如果我将要使用的一个CollationKey.所以我甚至将不再能够使用的集合。sort()方法...我非常的心存感激进的一个例子,是很容易理解和最有效率的执行情况进行排序收集的人物体使用CollationKey.
谢谢你!
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);
...
解决方案
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);
}
}
其他提示
- 创建一个SortedMap米,在那里T类型的对象,你想使用的排序
CollationKeys
.你可以使用TreeMap
作为执行情况 - 每个电子元件要排序,
m.put(collator.getCollationKey(e.{getStringYouWantToSortOn}), e);
迭代 m.values()
应该产生您的对象,按串你想要使用 CollationKeys
.
我相信这不是有效的,但它应的工作。
使用一个比较而不是使人相媲美。你比较可取2频散情况,并比较它们根据一些整理器的实例。然后打电话
Collections.sort(list, myPersonComparator);
不隶属于 StackOverflow