【发布时间】:2018-02-28 17:07:00
【问题描述】:
我在对数组列表进行排序时遇到问题。 在一个类中,我有两个不同对象的数组列表,我们可以将对象称为 Foo 和 Bar。
public class Foo() {
int value;
//Some other fields, and setters and getters.
}
public class Bar() {
int id;
//Same here...
}
所以列表 fooList 可以完全打乱。假设我有 16 个 Foo,但值为 5 的 Foo 可以在索引 13 上,依此类推。
我要做的是在这些值之后命令 barList 与 fooList 匹配。 如果值为 5 的 Foo 在索引 13 上,我希望值为 5 的 Bar 在索引 13 上。 我最后一次尝试是这样,但没有成功。
HashMap<Integer, Integer> positions = new HashMap<>();
for(int i=0;i<fooList.size();i++){
positions.put(foo.get(i).getValue, i);
}
Collections.sort(barList, new Comparator<Bar>(){
public int compare(Bar obj1, Bar obj2){
return positions.get(barList.indexOf(obj1)) -
positions.get(barList.indexOf(obj2));
}
});
有人知道如何以有效的方式做到这一点吗?
【问题讨论】:
-
创建一个可比较的类
FooBar。它包含对Foo的引用和对Bar的引用。根据您的标准,它与其他FooBar实例相当。 -
那么将两个列表从 0 排序到限制呢?它对你有用吗?
-
不应该
positions.get( obj1.getId() )吗? -
你能解释一下当 Foo (value) 和 Bar (id) 值不相交时的预期行为吗?
-
换句话说 - Bar 可以有一个 Foo 中不存在的 id 吗?