您可以使用闻起来像高阶函数的东西.也就是说,创建一个静态函数,该函数采用从Long到int(这是优先级)或数据的排序映射,并返回一个新的Comparator.
Foo类具有一个采用Orange的静态方法getComparator. Orange是具有方法getPriority的类,该方法获取ID并返回相应的优先级. getComparator方法构造一个新的Comparator对象.新的Comparator对象的compare方法带有两个ID.它查找两个ID的相应优先级并进行比较.
public interface Orange {
// Looks up id and returns the corresponding Priority.
public int getPriority(Long id);
}
public class Foo {
public static Comparator getComparator(final Orange orange) {
return new Comparator() {
public int compare(Long id1, Long id2) {
// Get priority through orange, or
// Make orange juice from our orange.
// You may want to compare them in a different way.
return orange.getPriority(id1) - orange.getPriority(id2);
};
}
}
我的Java有点生锈,因此代码可能有缺陷.不过,总体思路应该可行.
用法:
// This is defined somewhere. It could be a local variable or an instance
// field or whatever. There's no exception (except is has to be in scope).
Collection c = ...;
...
Orange orange = new Orange() {
public int getPriority(Long id) {
// Insert code that searches c.mySet for an instance of data
// with the desired ID and return its Priority
}
};
Collections.sort(c.myList, Foo.getComparator(orange));
我没有举一个橘子看起来的例子.