从上面的链接中,我希望我遵循被接受的答案。但我仍然得到例外。我正在使用 Java 6。
代码 :
public class GenericComparator implements Comparator<User> {
private static final String TAG = "java.util.Comparator.GenericComparator";
EnumComparatorObjectType mType;
public GenericComparator(EnumComparatorObjectType paramType) {
mType = paramType;
}
@Override
public int compare(User user1, User user2) {
if (user1 == null && user2 == null)
return 0;
try {
if (mType == EnumComparatorObjectType.ENUM_OBJECT_ADDRESS_BOOK_ENTRY) {
String name1 = user1.getUsername();
String name2 = user2.getUsername();
return name1.compareToIgnoreCase(name2);
} else if (mType == EnumComparatorObjectType.ENUM_OBJECT_PRESENCE) {
EnumPresence p1 = user1.getState();
EnumPresence p2 = user2.getState();
return p1.compareTo(p2);
}
} catch (Exception e) {
Logger.i(TAG, e.getMessage(), e);
}
return 0;
}
}
堆栈跟踪 :
java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeHi(TimSort.java:864)
at java.util.TimSort.mergeAt(TimSort.java:481)
at java.util.TimSort.mergeForceCollapse(TimSort.java:422)
at java.util.TimSort.sort(TimSort.java:219)
at java.util.TimSort.sort(TimSort.java:169)
at java.util.Arrays.sort(Arrays.java:2038)
at java.util.Collections.sort(Collections.java:1891)
at com.sample.app.adapters.BuddyListAdapter.filerContacts(BuddyListAdapter.java:144)
at com.sample.app.adapters.BuddyListAdapter.notifyDataSetChanged(BuddyListAdapter.java:126)
at com.sample.app.HomeActivity$2.onReceive(HomeActivity.java:325)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:763)
... 9 more