Sort algorithm changes for Java 7 throws IllegalArgumentException

1. Overview

Existing projects which are started with Java 5/6 and later migrated to Java 7 and Java 8 throws IllegalArgumentException while sorting the list. Here we will try to reproduce the issue and see the quick fix and fix.

2. Reproduce the issue

Run the below code few times (we may not reproduce the issue in 1 run).

throws the below Exception stacktrace

This is because of Updated sort behaviour for Arrays and Collections in Java 7. As per java 7 compatibility doc “The sorting algorithm used by java.util.Arrays.sort and (indirectly) by java.util.Collections.sort has been replaced. The new sort implementation may throw an IllegalArgumentException if it detects a Comparable that violates the Comparable contract. The previous implementation silently ignored such a situation.
If the previous behavior is desired, you can use the new system property, java.util.Arrays.useLegacyMergeSort, to restore previous mergesort behavior”.

3. Workaround

Quick fix for this issue is, add the below line to the JVM environment, which forces the application to use the previous algorithm.

4. Solution

To resolve the issue we need to change the code and need to obey Comparable contract.

Below code fixes the issue.

 

 

harinathk
 

Click Here to Leave a Comment Below 0 comments