tags:

views:

66

answers:

4

To make it easy, lets say I have an arraylist allBooks containing class "books" and an arraylist someBooks containing some but not all of the "books".

Using contains() method worked fine when I wanted to see if a book from one arraylist was also contained in another.

The problem was that this isn't working anymore when I save both of the Arraylists to a .bin file and load them back once the program restarts. Doing the same test as before, the contains() returns false even if the compared objects are the same (have the same info inside).

I solved it by overloading the equals method and it works fine, but I want to know why did this happen?

+6  A: 

You will have to provide your own hash code and equals implementation. By default, it will simply use pointer equality, which obviously fails after objects been 'cloned' (serialized/ deserialized cycle).

leppie
Thanks. Totally forgot that the pointers won't be the same after the load.
Milan
+2  A: 

What happened was that when you originally created the lists they both contained references to the same objects, but when you loaded them back in they both got separate copies of the same objects. Since each list got separate copies, they didn't contain the same references, meaning they didn't compare as equal without overloading the right method.

Gabe
+1  A: 

Assuming book is an object, by default Equals checks if the reference is equal. That cannot be the case when you load new objects. Overwriting the Equals method is a right approach.
Other options are to change Book to a struct, or using a more modern container, like a dictionary or hashtable, where you can store books by id.

Kobi
I wouldn't say that a dictionary/hashtable is "more modern" by any appreciable amount - they simply serve different purposes.
Marc Gravell
@Marc - fair point. I was obviously biased by versions of .net.
Kobi
+2  A: 

This sounds like the common issue of referential equality vs Equals, and is especially common with serialization. Override Equals (and GetHashCode) appropriately and you should be back in business.

For info, using ArrayList should generally be avoided unless you are using .NET 1.1 (or micro-framework), or have a very valid reason to do so; prefer the generic typed collections, such as List<T>.

Marc Gravell