It’s the table sorter stupid

Today, I just trapped into those pitfalls where thinking in terms of complexity fails. I got the following error message when sorting entries of a JFace TableViewer:

!MESSAGE Workaround for comparator violation:
    - set system property java.util.Arrays.useLegacyMergeSort=true
    - use a 1.6 JRE
message: Comparison method violates its general contract!

Here’s a part of the stack trace:

java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.util.TimSort.mergeLo(TimSort.java:747)
    at java.util.TimSort.mergeAt(TimSort.java:483)
    at java.util.TimSort.mergeCollapse(TimSort.java:408)
    at java.util.TimSort.sort(TimSort.java:214)
    at java.util.TimSort.sort(TimSort.java:173)
    at java.util.Arrays.sort(Arrays.java:659)
    at org.eclipse.jface.viewers.ViewerComparator.sort(ViewerComparator.java:189)

I thought that something with the TableViewer is wrong, … or with the data, … or with the label provider, … or with the content provider. Finally, I had a look at the sort algorithm:

int sortOrder = 0;
int size2 = result2.size();
int size1 = result1.size();
sortOrder = (size2 > size1) ? 1 : -1;

If size2 and size1 are the same it crashes, cause 0 shall be returned but in all cases -1 was returned. The following fix made it work.

int sortOrder = 0;
int size2 = result2.size();
int size1 = result1.size();
if(size2 != size1) {
	sortOrder = (size2 > size1) ? 1 : -1;
}

Stupid little mistake :-)!

Advertisements

About Philip Wenig

Founder of OpenChrom
This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to It’s the table sorter stupid

  1. opatry says:

    Hi,

    why not directly using `return result1.size() – result2.size();` ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s