1
我有一個自定義TreeSet的:TreeSet中不與自定義的比較正確排序
TreeSet<String> sortedOptionSet = new TreeSet<String> (new Comparator<String>() {
@Override
public int compare(String arg1, String arg2) {
if (arg1 == null || arg2 == null) {
return -1;
}
String o1 = arg1, o2 = arg2;
String k1 = "1", k2 = "2";
try{
if (o1.contains("P1")) {
return -1;
}
else if (o2.contains("P1")) {
return 1;
}
else if (o1.contains("P2")) {
return -1;
}
else if (o2.contains("P2")) {
return 1;
}
} catch (Exception e) {}
//If there is no rule for this combination, order them using key number ascending
int result = 1;
try {
Integer key1 = Integer.valueOf(k1);
Integer key2 = Integer.valueOf(k2);
result = key1.compareTo(key2);
if (result == 0) {
result = 1;
}
} catch (Exception e) {
}
return result;
}
});
sortedOptionSet.add("TEST1");
sortedOptionSet.add("P1");
sortedOptionSet.add("TEST2");
sortedOptionSet.add("P2");
sortedOptionSet.add("TEST3");
ArrayList<String> result = new ArrayList<String>();
result.addAll(sortedOptionSet);
for (String s : result) {
System.out.println(s);
}
我做P1的狀況都是最先想到的結果應該是:
P1
P2
TEST1
TEST2
TEST3
但結果回報
P2
P1
TEST1
TEST2
TEST3
我無法弄清楚爲什麼這是行爲。請幫忙。
您是否嘗試附加一個調試器並逐步調用您的比較方法? – jtahlborn 2015-02-09 17:12:12