我在 Java 方面遇到一些设计问题 Comparator
界面。
我有一个类,其中包含 Set
一个简单的自定义数据结构:
class data {
Long ID;
int Priority;
...
}
ID
s 是唯一的,因此可以使用 ID
获取整个数据。 。
和容器类:
class Container {
Set<data> mySet = ...;
List<Long> myList = ...;
...
}
出于某些不可避免的原因,我需要保留一个已排序的List
的data
ID 并行。我需要List
按 Priority
排序。
自从 Comparator
应该比较Priority
它应该实现 Comparator<int>
。但是List
仅包含ID
s 和 Priority
无法直接使用。
这就是问题所在。只有ID
在 List
。因此,Comparator 类无法访问 Priority
.
如何设计这样的概念?
最佳答案
你可以使用一些听起来像高阶函数的东西。也就是说,创建一个静态函数,它采用从 Long 到 int (这是优先级)或 data 的排序映射,并返回一个新的 Comparator。
类 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));
我还没有给出橙色外观的示例。
关于java - 根据另一个类中可用的参数对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12817616/