我有一组名称(a)和依赖项(b)的对象。我想以某种方式排列所有先前的依赖关系。所以我有这样的代码:TreeSet具有可比性,按递归依赖关系排序
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class Foo {
static class TestOrder implements Comparable<TestOrder> {
private final String a;
private final Set<String> b;
public TestOrder(String a, Set<String> b) {
this.a = a;
this.b = b;
}
public int compareTo(TestOrder o) {
if (o.b.contains(a))
return -1;
else
return 1;
}
@Override
public int hashCode() {
return a.hashCode();
}
@Override
public boolean equals(Object obj) {
return a.equals(obj);
}
public String toString() {
return a + " - " + b.toString();
}
}
public static void main(String[] args) {
Set<TestOrder> tos = new TreeSet<>();
tos.add(new Foo.TestOrder("a", new HashSet<String>() {{
add("b");
add("c");
}}));
tos.add(new Foo.TestOrder("e", new HashSet<String>() {{
add("a");
}}));
tos.add(new Foo.TestOrder("b", new HashSet<String>() {{
add("d");
add("c");
}}));
tos.add(new Foo.TestOrder("c", new HashSet<String>() {{ }}));
tos.add(new Foo.TestOrder("d", new HashSet<String>() {{ }}));
for (TestOrder to : tos) {
System.out.println(to.toString());
}
}
}
导致:
c - []
b - [d, c]
a - [b, c]
e - [a]
d - []
但是 - 由于B取决于d - 预期的结果将是:
c - []
d - []
b - [d, c]
a - [b, c]
e - [a]
我缺少什么?
非常酷,非常感谢! – KIC 2013-04-21 12:12:22
@KIC这不能解决问题,只会使问题更难找到。以这种顺序添加这些依赖关系,看看为什么:'a- [b]','c- [d]','b- [c]','d - []'。它应该产生'd- [],c- [d],b- [c],a- [b]',但是产生完全不同的输出([link](http://ideone.com/WKsLJQ) )。 – dasblinkenlight 2013-04-21 12:20:09
@dasblinkenlight是的,你是对的...最后,我不得不实施一个简单的拓扑排序算法...抱歉Michael Besteck我不得不改变正确的答案标签... – KIC 2013-04-21 13:55:52