我有一個「項目」類,它包含以下字段(簡稱):身份證(與商品相關的表的SQL Server上的主鍵),描述,序列(非空整數),並鏈接(父對象的ID)的參考,可以爲null)排序家長和孩子的使用Java
我想用Java來排序如下:
Id Sequence Link Description
1 1 null Item A
99 ..1 1 Son of A, first of the sequence
57 ..2 1 Son of A, second of the sequence
66 ..3 1 Son of A, third of the sequence
2 2 null Item B
3 3 null Item C
...
(我把圓點以便更好地觀察)
也就是說,我想某一個項目的子女來直接低於其父母,按「序列」字段排序。
我嘗試使用比較,但它失敗:
public class SequenceComparator implements Comparator<Item> {
@Override
public int compare(Item o1, Item o2) {
String x1 = o1.getSequence().toString();
String x2 = o2.getSequence().toString();
int sComp = x1.compareTo(x2);
if (sComp != 0) {
return sComp;
} else {
x1 = o1.getLink().toString();
x2 = o2.getLink() == null?"":o2.getLink().toString();
return x1.compareTo(x2);
}
}
}
我怎麼能這樣做?
你爲什麼不直接在SQL排序呢?這將是比較容易的方式,事實上,當你試圖在數字 – DamCx
項目進行排序這是一個[DAG](https://en.wikipedia.org/wiki/Directed_acyclic_graph)。您正在尋找[拓撲排序](https://en.wikipedia.org/wiki/Topological_sorting)。 –
我需要在Java中執行此操作。這不是我的決定 – aseolin