Comparing 2 ArrayLists

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));
 
B

Bob Grommes

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
 
E

Etienne Boucher

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


Etienne Boucher
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Fill Values in List 4
ArrayList memory problem 3
ArrayList 1
Combine Lists 1
Must be more elegant solution than this? 6
Logic question. Comparing 2 lists. 1
C# net 3.50 - List<T>.Count - bug ? 4
Comparing Lists 4

Top