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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@LouisWasserman: See my edit - it looks like a simple transform to a collection of integers would be more appropriate to me :)
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];
    }

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.