# Sorting an Array List

Sam Tilley
Ranch Hand
Posts: 160
Hi, i am having problems trying to sort an arraylist of different account codes.
I need to sort the account codes into ascending order with numbers ranging from 1 to 999. The problem is that doing
Collections.sort( orderId ) ;
but this prints it up with 11 after 109. E.g. it prints 1, 25, 100, 103, 109, 11, 110, 115, 119, 12, 121 etc etc.
So it only seems to see the first 2 digits.
I tried using a comparator with

but am not great on using it and came out with the same answer. Can anyone help me out as to how to sort by 3 digits, or just sort normally

Thanks
Sam

Sam Tilley
Ranch Hand
Posts: 160
I have actually now worked it out, by converting the strings to Integer objects and comparing the 2 objects. Out of interest can anyone tell me why it didn't do it on strings
Thanks

Michael Matola
whippersnapper
Ranch Hand
Posts: 1821
4
Originally posted by Sam Tilley:

I have actually now worked it out, by converting the strings to Integer objects and comparing the 2 objects.
Did you end up writing a Comparator that casts your Strings to Integers, or did you convert your original collection to Integers so you could rely on the fact that Integer already implements Comparable?
Out of interest can anyone tell me why it didn't do it on strings
The NameComparator you wrote relies on String.compareTo for comparing the two objects (as does your initial approach of the single-argument version of Collections.sort). Take a look at the API documentation on String.compareTo, especially the part on how it defines lexicographical ordering.

Marilyn de Queiroz
Sheriff
Posts: 9067
12

I'm wondering if this is in the proper forum. :roll:

Stu Glassman
Ranch Hand
Posts: 91
Think of what the numbers look like as Strings. 11 looks like "11" and 109 looks like "109". When comparing strings, you start with the leftmost character and work your way right, checking them by alphabetacal order. So, first it would compare '1' and '1'. They're equal, so go to the next character. Compare '1' to '0'. The '1' is bigger, so the "11" must be bigger than the "109".
Thinka about comparing names in abc order. For example, "Rose" and "Margie". Would you compare them like this:
Margie
--Rose
and compare 'M' to a blank space, or like this:
Margie
Rose--
and compare the 'M' to the 'R'?
Hope my nonsensical rambling has brought you peace of mind,
-Stu

Sam Tilley
Ranch Hand
Posts: 160
Cheers guys, Michael i ended up turning my strings into Integer objects rather than turn the whole collection into Integers as the list did contain a few account codes in as words which i had to take account so i set it up like so

Also i could easily adapt it to work on other objects such as date objects etc. etc.
Never know which forum to put these darn questions in, what exactly is the definition of java beginner, intermediate and advanced.
Cheers