我有一组具有名称(a)和依赖项(b)的对象。我想以解决所有先前依赖项的方式对对象进行排序。所以我有这个代码:
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]
我错过了什么?