Search code examples
javacollections

Collections.sort seems to generate incorrect results


The following code work except for specific inputs.

For instance the following input, -1795085364 stay as the last value, despite being the smallest. I am using java 13.

{306474574, 642543743, -752837577, 1030910205, 353252387, -1028696876, 2145575295, 2142057380, 66066294, -1795085364};

    private static void sortAndFilter(int[] nums) {
         List<int[]> numsIndexed = new ArrayList<int[]>(nums.length);
        for( int i = 0 ; i< nums.length; i++){
            int[] valAndIndex ={ nums[i],i };
            numsIndexed.add( valAndIndex );
        }
        Collections.sort(numsIndexed, (a,b) -> a[0] - b[0]);

        //rest of code here 
    }

Solution

  • (a, b) -> a[0] - b[0] is not a valid comparator. Nor is (a, b) -> a - b.

    Both fail to handle numerical overflow correctly. Use Integer.compare -- or, better, use Comparator.comparingInt(a -> a[0]).