To sort the ArrayList, use the Sort method, which has three overloaded forms:
aList.Sort()
aList.Sort(comparer)
aList.Sort(startIndex, endIndex, comparer)
Code language: CSS (css)
The ArrayList’s Sort method doesn’t require you to pass the name of the ArrayList to be sorted as an argument; unlike the Sort method of the Array class, this is an instance method and sorts the ArrayList object to which it’s applied. aList is a properly declared and initialized ArrayList object. The first form of the Sort method sorts the ArrayList alphabetically or numerically, depending on the data type of the objects stored in it. If the items are not all of the same type, an exception will be thrown. You’ll see how you can handle this exception shortly.
If the items stored in the ArrayList are of a data type other than the base data types, you must supply your own mechanism to compare the objects. The other two forms of the Sort method use a custom function for comparing items; you will see how they’re used in the section “Custom Sorting,” later in this chapter. Notice that there is no overloaded form of the Sort method that sorts a section of the ArrayList.
If the list contains items of widely different types, the Sort method will fail. To prevent a runtime exception (the InvalidOperationException), you must make sure that all items are of the same type. If you can’t ensure that all the items are of the same type, catch the possible errors and handle them from within a structured exception handler, as demonstrated in Listing 10.4.
Listing 10.4: Foolproof Sorting
Dim sorted As Boolean = True
Try
aList.Sort()
Catch SortException As InvalidOperationException
MsgBox("You can't sort an ArrayList whose items " & _
"aren't of the same type")
sorted = False
Catch GeneralException As Exception
MsgBox("The following exception occurred:" & _
vbCrLf & GeneralException.Message) sorted = False
End Try
If sorted Then
{ process sorted ArrayList}
Else
{ process unsorted list}
End If
Code language: PHP (php)
The sorted Boolean variable is initially set to True because the Sort method will most likely succeed. If not, an exception will be thrown, in which case the code resets the sorted variable to False and uses it later to distinguish between sorted and unsorted collections. Notice the two clauses of the Catch statement that distinguish between the most common exception that the Sort method can throw (the invalid operation exception) and any other type of exception.
The Sort method can’t even sort a collection of various numeric data types. If some of its elements are doubles and some are integers or decimals, the Sort method will fail. You must either make sure that all the items in the ArrayList are of the same type, or provide your own function for comparing the ArrayList’s items. The best practice is to make sure that your collection contains items of the same type. If a collection contains items of different types, how likely is it that you’ll have to sort such a collection?