FirmView
FirmView

Reputation: 3150

Sorting array not working

public static void main(String[] args) {       
   String[] errorStr = new String[] {
       "Line No: " + " " + 1,
       "Line No: " + " " + 11,
       "Line No: " + " " + 10,
       "Line No: " + " " + 2,
       "Line No: " + " " + 3
   };

   Arrays.sort(errorStr);       
   for(Object obj : errorStr){
       System.out.println(obj);
   }
}

Can someone point why the sorting is not working here?

expected is,

Line No: 1
Line No: 2
Line No: 3
Line No: 10
Line No: 11

Actual is, 
Line No: 1
Line No: 11
Line No: 10
Line No: 2
Line No: 3

Upvotes: 1

Views: 1084

Answers (2)

Ben
Ben

Reputation: 2500

As Jon said, it's sorting the elements lexicographically. You could try making an int array with the desired numbers, sorting that, and then concatenating "Line No: " to each element. I guess the solution strategy kind of depends on how the elements got out of order in the first place...

Edit: heres the code sample

    int[] errorInt = new int[]{ 1,11,10,2,3} ;
    String[] errorString = new String[ errorInt.length ];
    Arrays.sort(errorInt);
    for( int i = 0; i < errorInt.length; i++) {
        errorString[i] = "Error No:" + errorInt[i];
    }

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500055

It's sorting in lexicographic order - and lexicographically "11" comes before "2", and "Line No: 11" comes before "Line No: 2".

If you want "smarter" sorting, you'll need to implement a Comparer<String> which performs appropriate parsing in order to compare strings.

If all your values are actually "Line No: " followed by a value, I'd just transform them into an array or list of integers, as that's the natural data you're trying to represent... and sorting an array of int values will work as you expect.

Fundamentally, this is what you get for treating numbers as strings :)

Upvotes: 7

Related Questions