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.
- What is the property of IComparable implementation, that can possibly error out the mixure?
- How does it recognize all integers or all strings for sorting?
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
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>