Arraylist cannot compare objects after loading them from disk

To simplify, let's say I have arraylist allBooksa class containing a “book” and arraylist someBookscontaining some, but not all, “books”.

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

The problem was that this no longer works when I save both Arraylists in a .bin file and load them after the program is reloaded. Performing the same test as before, the contains () function returns false, even if the objects being compared are the same (have the same information inside).

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

+3
source share
4 answers

You will need to provide your own hash code and be equal to the implementation. By default, it simply uses pointer equality, which obviously fails after the objects have been "cloned" (serialized / deserialized loop).

+6
source

It so happened that when you initially created lists, they both contained links to the same objects, but when you downloaded them back, they had separate copies of the same objects. Since each list received separate copies, they did not contain the same links, that is, they were not compared as equal without overloading the correct method.

+2
source

vs Equals . Equals ( GetHashCode) , .

, , ArrayList, .NET 1.1 ( micro-framework), ; , List<T>.

+2

, book , Equals , . , . Equals - .
- book , -, id.

+1

Source: https://habr.com/ru/post/1742756/


All Articles