问问题
917 次
2 回答
1
你可以使用一些闻起来像高阶函数的东西。也就是说,创建一个静态函数,该函数采用从 Long 到 int(这是优先级)或数据的排序映射并返回一个新的比较器。
Foo 类有一个getComparator
采用 Orange 的静态方法。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<Long> getComparator(final Orange orange) {
return new Comparator<Long>() {
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));
我没有举例说明橙色的外观。
于 2012-10-10T11:11:42.373 回答
0
我假设你有一个List<Data>
存储在某个地方。在比较器中,你需要getDataById
从你的数据类中调用一个方法,并通过优先级排序。
检查下面的代码..我已将单个类用于多种目的..
理想情况下,您希望将其分解为更多类..但这只是一个演示,如何实现您想要的..
class Container {
// List of Data instances created..
// This list has to be static, as it is for a class,
// and not `instance specific`
public static List<Data> dataList = new ArrayList<Data>();
// List of Ids, that you want to sort.
private List<Long> idList = new ArrayList<Long>();
// Populate both the list..
// Have a method that will iterate through static list to
// find Data instance for a particular id
public static Data getDataById(long id) {
// Find Data with id from the list
// Return Data
}
public void sortList() {
Collections.sort(idList, new MyComparator());
}
}
public MyComparator implements Comparator<Long> {
public int compare(Long int1, Long int2) {
Data data1 = Container.getDataById(int1);
Data data2 = Container.getDataById(int2);
return data1.getPriority() - data2.getPriority();
}
}
于 2012-10-10T11:03:26.480 回答