Comparing 2 ArrayLists

  • Thread starter Thread starter Bob Rundle
  • Start date Start date
B

Bob Rundle

I try to compare two array lists. Do I have to do it element by element? I
can't believe you can sort an array list but you can't compare them.

The following code will assert...

ArrayList list1 = new ArrayList();
list1.Add("a");
ArrayList list2 = new ArrayList();
list2.Add("a");
Debug.Assert(Object.Equals(list1,list2));
 
As you've probably noticed, the docs don't indicate that Equals has been
overridden for ArrayList, but just for the heck of it, I'd check:

Debug.Assert(list1.Equals(list2));

I have no idea why Object.Equals(list1,list2) would be true. You are
comparing object references, and the static Equals() method certainly isn't
going to behave differently for ArrayList objects. And list1 and list2 are
different references even if both instances happen to have one item with the
same string value.

As far as I know you have to compare item by item. One reason might be that
an ArrayList takes objects, and those objects could box anything.

Just for the heck of this I ran the following in C# Express 2005 Beta, using
List<T>, the generic version of ArrayList:

List<int> list1 = new List<int>();
list1.Add(1);
list1.Add(3);
list1.Add(5);
list1.Add(7);
List<int> list2 = new List<int>();
list2.Add(1);
list2.Add(3);
list2.Add(5);
list2.Add(7);
Console.WriteLine("Object.Equals(list1,list2)={0}",Object.Equals(list1,list2
));
Console.WriteLine("list1.Equals(list2)={0}", list1.Equals(list2));
Console.Write("Press any key ...");
Console.ReadLine();

The result for both tests was false, as I'd expect. And, I don't see any
new methods for testing equality either.

--Bob
 
There is also no easy way that I have found to compare two arrays or two
ranges within arrays.


Etienne Boucher
 
Back
Top