除非我在本地声明,否则项目不会添加到 HashSet

Item not adding to HashSet unless I declare it locally

我有一个 HashSet<User> 和一个在 while 循环外声明的用户,在循环内我用 setter 方法设置名称,然后将用户添加到 HashSetadd(User)

这似乎只更新 HashSet 中的单个用户。只有当我在 while 循环中声明用户时,每次都会将新用户添加到 HashSet

我在想这是因为如果HashSet add() method接收到一个与集合中当前对象具有相同内存地址的对象,它只会更新该对象而不会向HashSet添加另一个新对象。这个对吗?

然后在循环中实例化 User 将导致它具有不同的内存地址,因此将作为新对象添加到 HashSet

我可以把代码放在这里,但这是为了作业,我想我的教授不希望我分享代码。如您所见,我的问题更多是关于 Java 语言,而不是关于我的作业。但是,如果每个人都绝对需要查看代码,我会 post 提供一些有用的东西。

I am thinking this is because if the HashSet add() method receives an object with the same memory address as an object currently in the set, it will only update the object and not add another new object to the HashSet. Is this correct?

没错。根据定义,HashSet 将只允许每个唯一对象中的一个。但是,关于更新对象的部分与其在 HashSet 中的成员资格无关。由于 HashSet 仅包含引用,您对对象所做的任何更改(在 while 循环中或之外)都会自动反映在 HashSet 中。

Then instantiating the User within the loop will cause it to have a different memory address

也对。对于每个实例化,您将对每个对象有不同的引用。 HashSet 将存储一个且仅存储一个。