即使 Comparator 似乎被正确调用,Collections.sort 似乎也没有对我的 ArrayLists 进行排序。似乎在对每个 Arraylist 执行排序后,排序不会坚持,ArrayLists 中的项目仍保持其原始顺序。
这就是我如何遍历每个 Arraylist 并对它们进行排序,然后打印它们以检查:
public void SortCreatures ( int x ) {
for ( Party p : SorcerersCave.theCave.parties ) {
//cycles through parties to sort each ones ArrayList members
switch ( x ) {
case 0 :
Collections.sort( p.members, new compareThings.CEmpathy());
case 1 :
Collections.sort( p.members, new compareThings.CFear() );
case 2 :
Collections.sort( p.members, new compareThings.CCarry() );
}
}
generateInterface.theGame.printOutput( "Displaying Sorted Creatures:" );
for ( Party p : SorcerersCave.theCave.parties ) {
generateInterface.theGame.printOutput( "" + p );
for ( Creature c : p.members ){
generateInterface.theGame.printOutput( "\t" + c );
}
}
}
这是使用案例 0 时的输出:(第 5 列中的第 5 个 Int 是 Empathy):
Displaying Sorted Creatures:
10000 - School//Party for refference
20002 - Vampire - Loren - 10000 - 3 - 28 - 59
20003 - Leprechaun - Claretta - 10000 - 48 - 64 - 97
20000 - Witch - Catheryn - 10000 - 5 - 77 - 98
20001 - Kobold - Kim - 10000 - 60 - 42 - 208
10001 - Gaggle//Party for refference
20004 - Elf - Bob - 10001 - 51 - 51 - 155
20006 - Yeti - Soraya - 10001 - 28 - 30 - 209
20007 - Pixie - Dusty - 10001 - 8 - 74 - 242
20005 - Hero - Sol - 10001 - 90 - 24 - 273
10002 - Gang
...
这是 Empathy 的比较器:(第 5 列中的第 5 个 Int 是 Empathy)
public static class CEmpathy implements Comparator< Creature > {
@Override
public int compare( Creature o1, Creature o2 ) {
int c1 = o1.getEmpathy();
int c2 = o2.getEmpathy();
System.out.println( c1 + " & " + c2 );
if ( c1 < c2 ) return -1;
else if ( c1 == c2 ) return 0;
else return 1;
}
}
让我感到困惑的是 Comparator 似乎执行正确,这是每对正在比较的数字的打印。
60 & 5
3 & 60
3 & 60
3 & 5
48 & 5
48 & 60
90 & 51//new party
28 & 90
28 & 90
28 & 51
8 & 51
8 & 28
...
我在每一步都打印了 2 个小时,但一切似乎都在正常执行。任何帮助将不胜感激。