1. Computing & Technology

Discuss in my forum

The IComparable Interface: Using a Custom Sort

Finishing the System

By , About.com Guide

We're almost finished, the only task left is to add the code for the CompareTo Function. At this point, it's useful to go back and reconsider how we got here. We're actually coding an implementation of the Sort method of the Array object. When Sort runs, it's going to check whether there is a custom CompareTo Function available. If there is, then Sort runs it. If not, Sort uses a default that simply does an alphabetic comparison. But the main thing that CompareTo has to do is return an integer to Sort. An integer that is ...

  • Less than zero -- This instance is less than obj.
  • Zero -- This instance is equal to obj.
  • Greater than zero -- This instance is greater than obj.

Here's the code:


Public Function CompareTo(ByVal obj As Object) As Integer _
    Implements System.IComparable.CompareTo
    Dim compFH As FHData = CType(obj, FHData)
    ' Console.WriteLine(compFH.FH & " - " & Me.FH)
    If compFH.FHScore > Me.FHScore Then
        Return 1
    ElseIf compFH.FHScore < Me.FHScore Then
        Return -1
    Else
        Return 0
    End If
End Function

But ... What is "obj"???

Remember that this function is called by the Sort method of the array. The obj parameter is the "previous" element that Sort needs to compare with the "next" one. This code also includes a commented debug statement that you can uncomment to see what's actually happening more clearly. The .NET Sort method simply swaps elements in the array until it's sorted. You can find lots of references that explain how a sort algorithm does that.

The same Sort statement still works since all of the actual processing happens in the class code.


Array.Sort(HHHarray) ' Call the Sort method

This will do the job of sorting the array, but we can customize the result by Overriding the ToString method in the FHData class.


Public Overrides Function ToString() As String
    Return "Score: " & FHScore & " - " &
    FH & " " &
    FHHasCar & " a car and has " &
    FHHasMoney & " money. He's " &
    FHIsHunkOrJunk & "."
End Function

After all this, Ruth Leslie can now ruthlessly go after the optimum target in her high school:

--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

Click here to download the complete HHHReport program.

©2012 About.com. All rights reserved.

A part of The New York Times Company.