Arraylist Sort with IComparable

Introduction

The ArrayList class offers capabilities not available in traditional arrays. This class dynamically resizes and also has a built-in sort feature that can save many hours of development. It is also extensible to handle non-standard data types.

In C# (C sharp) the ArrayList sort method handles standard types such as int and String, but must be extended via the IComparable interface in order to process user-defined typed. The IComparable interface is best learned through example: there is no reason to create this extension 'from scratch'. In this tutorial we present a simple implementation of the IComparable interface that supplements the Sort method of the ArrayList class. We also explain the programming and demonstrate the results. Our example code can be enhanced and improved by students of C# (C sharp) in order to gain a better understanding of the technology.

Motivation

In order to fully leverage the power of the ArrayList class, programmers need to have a thorough understanding of the IComparable interface. Entities in the real world are rarely represented by simple data types, therefore ArrayList data items are often populated by objects that cannot be sorted by the built-in capabilities of the ArrayList sort feature. Certainly a simple list of integers or strings can be sorted without implementing an IComparable interface, but more complex programmer-defined classes cannot.

Eventually every C# programmer will realize the need to sort a list of programmer-defined objects. This can be easily accomplished by leveraging the IComparable interface.

Introducing the example program

Our example program is implemented in C# (C sharp) using Visual Studio 2011 SP 1. The code is sufficiently straightforward to be portable to other versions of Visual Studio. The completed program appears at the end of the tutorial. We will introduce the program piecemeal and discuss salient concepts along the way.

Overview of the program

Our program includes a programmer-defined class, Car. This class exists solely to illustrate the application of the IComparable interface. It is not intended to be useful in the real world. The class contains only two properties: topSpeed and model. The class includes only one method, which is a constructor.

Our Car class also implements the IComparable interface. Note the reference to the interface name in the first line of the class:

class Car : IComparable

This interface requires the definition of a method with this signature:

public int CompareTo(object c)

The signature is significant because the Sort method defined in the ArrayList class has already been programmed to look for a method with such a signature.

We are responsible for programming the CompareTo method such that is properly compares two objects of type Car and returns the result of the comparison. For our purposes, we have arbitrarily decided to compare the top speed of the two car objects. The car with the higher top speed will be 'greater' than the other car.

Keep in mind that we, as programmers, can implement any comparison logic as long as it's wrapped in a CompareTo method with the proper signature. If we do not have system design responsibilities, it may be prudent to look at the design documentation or talk to the project analysts to learn precisely how the objects should be compared.

Here is our completed implementation of the CompareTo method:

public int CompareTo(object c)
{
	return CompareTo((Car)c);
}

Note that our method, defined above, references another method with the same name but a different signature:

public int CompareTo(Car c)
{
  int status;
  Car compare = c as Car;
  if (this.topSpeed > compare.topSpeed) 
    status = 1; 
  else 
    status = -1;

  return status;
}
 

We followed this strategy because the IComparable interface requires what amounts to a CompareTo method with a generic argument (Object c), but we know that our CompareTo method will always deal with Car objects. To that end, we define a more application-specific CompareTo method that deals specifically with Car objects. The generic CompareTo method calls the specific CompareTo method.

Discussion of the overall program

Line 16: declare and instantiate the ArrayList object. Note that an ArrayList object can contain heterogeneous references to objects. In our example, we insert only references to Car objects. We still need to implement the IComparable interface because an ArrayList class does not know how to sort our Car objects unless we provide a CompareTo method.

Lines 17-22: Add a few Car objects to the ArrayList. Each Car object has a value for the properties topSpeed and model, which are passed to the constructor of the object.

Lines 24-28: Print the contents of the ArrayList by traversing it from beginning to end. The order of the objects will be the order that they were inserted into the ArrayList object.

Line 30: Call the Sort method that is a member of the ArrayList class. This method will call our CompareTo method each time that two Car objects need to be compared.

Lines 31-34: Print the contents of the ArrayList again by traversing it from beginning to end. The order of the objects will be the order that they were sorted.

Line 61: Changing the sort order is accomplished by altering the logic in this line. The programmer may choose to implement a comparison based on some other criteria rather than topSpeed. Note that the sort can be changed from ascending to descending by simply inverting the relational operator in this line.

The complete program

// An Introduction to the IComparable Interface using  C# (C Sharp)
// (C) nicomp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ArrayList_and_iComparable_in_C_Sharp
{
    class main 
    {
        public static void Main(String[] args)
        {
            Console.WriteLine ("ArrayList and iComparable");
            ArrayList myCars = new ArrayList();
            myCars.Add(new Car(100, "Springbok"));
            myCars.Add(new Car(200, "Maniac Speedster"));
            myCars.Add(new Car(75, "Yugo"));
            myCars.Add (new Car(55, "Chevert"));
            myCars.Add(new Car(225, "Porch"));
            myCars.Add(new Car(110, "Grand Amigo XE"));

            Console.WriteLine("The sorted list...");
            foreach (Car car in myCars)
            {
                Console.WriteLine(car.topSpeed + "\t" + car.model);
            }

            myCars.Sort();
            Console.WriteLine("\n**************************\nThe sorted list...");
            foreach (Car car in myCars) {
                Console.WriteLine(car.topSpeed + "\t" + car.model);
            }
        }
    }

    /// <summary>
    /// Implement the IComparable interface
    /// </summary>
    class Car : IComparable
    {
        private int intTopSpeed;
        String strModel;

        public Car(int topSpeed, String model) { this.topSpeed = topSpeed; this.model = model; }
        public int topSpeed
        {
            get {return intTopSpeed;}
            set {intTopSpeed = value;}
        }
        public String model
        {
            get { return strModel; }
            set { strModel = value; }
        }
        public int CompareTo(Car c)
        {
            int status;
            Car compare = c as Car;
            if (this.topSpeed > compare.topSpeed) status = 1; else status = -1;
            return status;
        }
        public int CompareTo(object c)
        {
            return CompareTo((Car)c);
        }
    }
}
The output of the program
The output of the program

Conclusion

The IComparable interface increases the flexabillity of the ArrayList class by allowing programmers to implement custom comparison logic for programmer-defined data types.

We have demonstrated the use of the IComparable interface through the introduction of a basic C# (C sharp) program.

More by this Author


Comments 8 comments

psychicdog.net profile image

psychicdog.net 5 years ago

I notice you used the term signature...is this the new name for parameter?


drbj profile image

drbj 5 years ago from south Florida

nicomp - say what?


nicomp profile image

nicomp 5 years ago from Ohio, USA Author

@psychicdog.net: The signature of a method is the method name and parameter list. It's sufficient to make the method unique.

@djbj: My feelings precisely.


psychicdog.net profile image

psychicdog.net 5 years ago

Thanks Nicomp - I haven't ventured into c# - what is it used for mostly? Windows platform?


nicomp profile image

nicomp 5 years ago from Ohio, USA Author

@psychicdog.net: Yes, it's a Microsoft invention that is supported by .Net and Visual Studio. It's very much like Java, syntactically.


psychicdog.net profile image

psychicdog.net 5 years ago

so I suppose we'll see it on smartphones that use Microsoft - I think I heard Nokia and Microsoft are developing Windows platform in this arena so we might see a Nicomp Frog Game app to download on our smartphone screens that use C#!?


nicomp profile image

nicomp 5 years ago from Ohio, USA Author

psychicdog.net : I'm making so much money on HubPages that I have no time to write a Frog game. I spend my time protecting the frogs. and penguins. and ducks.


psychicdog.net profile image

psychicdog.net 5 years ago

Noahcomp!

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working