如何在java hashset中查找并返回对象
根据 HashSet javadoc,HashSet.contains 仅返回布尔值。如何在 hashSet 中“查找”对象并修改它(它不是原始数据类型)?
我看到 HashTable 有一个 get() 方法,但我更喜欢使用该集合。
According to the HashSet javadoc, HashSet.contains only returns a boolean. How can I "find" an object in a hashSet and modify it (it's not a primitive data type)?
I see that HashTable has a get() method, but I would prefer to use the set.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以删除一个元素并添加另一个元素。
修改哈希集中的对象会导致灾难(如果修改改变了哈希值或相等行为)。
You can remove an element and add a different one.
Modifying an object while it is in a hash set is a recipe for disaster (if the modification changes the hash value or equality behavior).
引用一下Sun java.util.HashSet股票的出处:
所以你是在花钱买一张地图,你不妨使用它。
To quote the source of the stock Sun java.util.HashSet:
So you are paying for a map, you might as well use it.
您可以迭代该集合来查找您的对象。
来自 API 文档的警告 不过:
“注意:如果将可变对象用作集合元素,则必须格外小心。如果对象的值以影响等于比较的方式更改,而该对象则不会指定集合的行为是集合中的一个元素。”
You can iterate through the set to find your object.
A word of warning from the API doc though:
"Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set."
像这样的东西:
Something like:
我遇到了同样的问题并提出了以下解决方案(它应该实现 Set 接口,但并非所有方法都在这里)
I encountered the same problem and came up with the following solution (it should implement the Set interface but not all methods are here)