我有一些Java Comparator接口的设计问题。
我有一个包含简单定制数据结构的Set的类:
class data {
Long ID;
int Priority;
...
}ID是唯一的,因此可以使用ID获取整个数据。
和容器类:
class Container {
Set<data> mySet = ...;
List<Long> myList = ...;
...
}由于一些不可避免的原因,我需要并行地保持data ID的排序List。我需要按Priority对List进行排序。
因为Comparator应该比较Priority,所以它应该实现Comparator<int>。但List仅包含ID%s,并且Priority%s不可直接使用。
这就是问题所在。List中只有ID。因此,比较器类不能访问Priority。
我该如何设计这样的概念呢?
发布于 2012-10-10 19:11:42
你可以使用一些看起来像高阶函数的东西。也就是说,创建一个静态函数,该函数接受从Long到int (这是优先级)或data的映射,并返回一个新的比较器。
类Foo有一个静态方法getComparator,它接受一个橙色参数。橙色是一个类,它有一个getPriority方法,它接受一个ID并返回相应的优先级。getComparator方法构造一个新的Comparator对象。新的Comparator对象的compare方法有两个ID。它查找两个It的对应优先级,并对它们进行比较。
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-10 19:03:26
我假设您在某个地方存储了一个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();
}
}https://stackoverflow.com/questions/12817616
复制相似问题