[英]sort a List based on a parameter available in another class
我在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
, Priority
不能直接使用。
这就是问题。 List
只有ID
。 因此,Comparator类无法访问Priority
。
我如何设计这样的概念?
您可以使用闻起来像高阶函数的东西。 也就是说,创建一个静态函数,该函数采用从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<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));
我没有举一个橘子看起来的例子。
我假设您有一个List<Data>
存储在某个位置。在Comparator中,您需要从数据类中调用getDataById
方法,并通过Priority进行排序。
检查下面的代码..我出于多种目的使用了单个类。
理想情况下,您希望将其分为更多的类 ..但这只是一个演示 ,如何实现所需的内容。
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.