1
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
FirmView
  • 3,130
  • 8
  • 34
  • 50

2 Answers2

7

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 :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Alternately, write a special class that holds the line number in an appropriate `int` field and implements `Comparable`, and sort those before converting them to `String`. – Louis Wasserman Jul 07 '12 at 15:45
  • 2
    @LouisWasserman: See my edit - it looks like a simple transform to a collection of integers would be more appropriate to me :) – Jon Skeet Jul 07 '12 at 15:46
  • 1
    See: [sort on a string that may contain a number](http://stackoverflow.com/questions/104599/sort-on-a-string-that-may-contain-a-number) – Keith Flower Jul 07 '12 at 15:47
2

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];
    }
Ben
  • 2,430
  • 3
  • 22
  • 24
  • i am having similar issue, your solution sounds like it may work for me. Do you have a really quick and dirty example you can edit in? – ShawnDaGeek Jul 07 '12 at 15:51