从磁盘加载后,Arraylist 无法比较对象 [英] Arraylist can't compare objects after they are loaded from disk
问题描述
为了简单起见,假设我有一个 arraylist allBooks
包含类books"和一个 arraylist someBooks
包含一些但不是全部books".
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".
当我想查看一个数组列表中的一本书是否也包含在另一个数组列表中时,使用 contains() 方法效果很好.
Using contains() method worked fine when I wanted to see if a book from one arraylist was also contained in another.
问题是当我将两个 Arraylists 保存到 .bin 文件并在程序重新启动后重新加载它们时,这不再起作用.进行与之前相同的测试,即使比较的对象相同(内部具有相同的信息), contains() 也会返回 false.
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).
我通过重载 equals 方法解决了这个问题并且它工作正常,但我想知道为什么会发生这种情况?
I solved it by overloading the equals method and it works fine, but I want to know why did this happen?
推荐答案
您必须提供自己的哈希代码和 equals 实现.默认情况下,它将简单地使用指针相等性,这在对象被克隆"(序列化/反序列化循环)后显然会失败.
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).
这篇关于从磁盘加载后,Arraylist 无法比较对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!