简体   繁体   中英

Arraylist can't compare objects after they are loaded from disk

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?

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).

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.

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> .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM