Post

ArrayList item comparison

In .NET, Tech/Hacks on June 6, 2008 by Sid

What’ll be the output of the following piece of code (asked here)?

ArrayList a = new ArrayList();
ArrayList b = new ArrayList();

a.Add(1);
b.Add(1);
a.Add(2);
b.Add(2.0);

Console.WriteLine(a[0] == b[0]);
Console.WriteLine(a[1] == b[1]);

One might expect…

True
True

But what you’d actually get is…

False
False

…because of boxing.

a.Add(1) boxes the integer 1 into an object and stores it in a, while b.Add(1) boxes the integer 1 into a separate object and stores it in b. Since a[0] and b[0] are going to be different objects, the check is going to fail. Same logic applies when comparing a[1] and b[1].

However, it gets interesting. If you tried to do a similar thing in VB.NET, the output would be different.

So with a code like this…

Dim a as new ArrayList()
Dim b as new ArrayList()

a.Add(1)
b.Add(1)
a.Add(2)
b.Add(2.0)

Console.WriteLine(a(0) = b(0))
Console.WriteLine(a(1) = b(1))

The output is going to be…

True
True

Surprised :) Well, VB.NET compiler translates the equality check (“=”) to a call to a helper function part of VB.NET runtime which would cast the left and right hand sides appropriately before comparison. In the first case, it would compare the two objects as integers, while in the second case it would compare the two objects as doubles after converting the integer on left hand side to a double.

That’s why we have generics – no surprises like these…


2 Responses to “ArrayList item comparison”

  1. [...] Damian Brady wrote a beautiful answer in his blog as did Ricky in his blog Crazy Pointer and Siddharth in his blog Some Creativity. [...]

  2. What about VB.NET with
    Dim a as new ArrayList()
    Dim b as new ArrayList()

    a.Add(“String”)
    b.Add(“String”)

    Console.WriteLine(a(0) = b(0))

    Do strings get cast?

    And what about

    Dim a as new ArrayList()
    Dim b as new ArrayList()

    a.Add(“String1″)
    a.Add(“String2″)
    b.Add(“String1″)
    b.Add(“String2″)

    Console.WriteLine(a = b)

    ‘ I suspect the above prints false.
    ‘ Is there a function to call instead of =
    ‘ that would determine that ArrayList a and ArrayList b are the same.
    ‘ Or do I have to write one ?

Leave a Reply