Question Can someone explain this, how can this code sorting an object within arraylist ?

phicha

Well-known member
Joined
May 11, 2009
Messages
45
Programming Experience
Beginner
VB.NET:
Class Murid
        Implements IComparable
        Public strNama, strKelas As String

        Public Function CompareTo(ByVal obj As Object) As Integer _
   Implements System.IComparable.CompareTo
            Dim Compare As Murid = CType(obj, Murid)
            Dim result As Integer = Me.strKelas.CompareTo(Compare.strKelas)
            Return result
        End Function
    End Class

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim ara As New ArrayList
        Dim murid As New Murid
        murid.strNama = "Philip"
        murid.strKelas = "2"
        ara.Add(murid)
        murid = New Murid
        murid.strNama = "Vivi"
        murid.strKelas = "1"
        ara.Add(murid)

        For Each murid In ara
            MsgBox(murid.strNama)
        Next

        ara.Sort()

        For Each murid In ara
            MsgBox(murid.strNama)
        Next

    End Sub

please someone help me explain how this code work ? i try it and it work finely, but still i dont know how it working.

thanks,
 
Last edited by a moderator:
First up, I have removed your additional questions as they were not related to the topic of this thread. Please keep each thread to a single topic and each topic to a single thread. Each of those additional question was on a topic unrelated to this thread or each other so they each belong in a new thread of their own.

As for this topic, when you call Sort on a list it will, by default, use the list item type's own IComparable implementation. In order to sort a list you must perform a series of comparisons between pairs of items. That's what that CompareTo method is for. Internally, Sort will compare two items and either leave them or swap them, depending on the result of the CompareTo method. Exactly which pairs of items get compared depends on the sorting algorithm in use but all sorting depends on multiple comparisons of pairs of items.

For more information on sorting lists you might like to read my blog on the subject. Part 1 is dedicated to the IComparable interface but make sure that you read parts 2 and 3 as well.
 
Back
Top