2

When I write this code, I get an error on the Sort() Method.

       ArrayList al = new ArrayList();
        al.Add("I");
        al.Add("am");
        al.Add(27);
        al.Add("years old");


        foreach (object o in al)
        {
            Console.Write("{0} ", o.ToString());
        }

        al.Sort();
        Console.WriteLine();
        foreach (object o in al)
        {
            Console.Write("{0} ", o.ToString());
        }

Well, I can understand that the Sort Method failed since I included both String and integer in the collection.

But it doesn't error out when I have all strings or all integers. It does the sorting really well.

  1. What is the property of IComparable implementation, that can possibly error out the mixure?
  2. How does it recognize all integers or all strings for sorting?
1
  • Incidentally, ArrayList is obsolete. Try List<T>. Commented Aug 12, 2010 at 3:27

2 Answers 2

2

It uses the compareTo of the Object. Inside the compareTo, the object will check the type of the compared object and can produce error there like this:

String : IComparable

public int compareTo(Object s) {
  if (!(s is String)) {
    throws new Exception();
  }
  //do the job
}

The sort method of the array will loop through elements of the array and call the compareTo method on each element to compare with other elements

I also recommend you to use generics so you can never accidentially put different kinds of objects inside. Use ArrayList<String>

Sign up to request clarification or add additional context in comments.

2 Comments

You mean if (!(s is Int32)) ?
No I mean if s is not a String, then throw an exception. The example I give is wrong
0

You can use a delegate to create a custom sorting. Below, it is sorting custom list of Address based on Address.AddressId

// sort list in descending order
addressList.Sort(delegate(Address a1, Address a2) { return a2.AddressId.CompareTo(a1.AddressId); });

You can create any kind of logic for this, even getting both parameters to delegate as objects and then testing their type, and compare based on that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.