Java:从HashSet中检索元素 [英] Java: Retrieving an element from a HashSet
问题描述
希望有人能解释为什么我无法从 HashSet
中检索元素。
Hoping someone can explain why I cannot retrieve an element from a HashSet
.
考虑我的 HashSet
包含 MyHashObjects
的列表及其 hashCode()
和 equals()
方法正确覆盖。
Consider my HashSet
containing a list of MyHashObjects
with their hashCode()
and equals()
methods overridden correctly.
我希望做的是构造 MyHashObject
我自己,并将相关的哈希码属性设置为某些值。
我可以查询 HashSet
,看看集合中是否有等价对象使用 contains()
方法。
所以即使 contains()
为2个对象返回true,它们也可能不是 ==
true 。
What I was hoping to do was to construct a MyHashObject
myself, and set the relevant hash code properties to certain values.
I can query the HashSet
to see if there "equivalent" objects in the set using the contains()
method.
So even though contains()
returns true for the 2 objects, they may not be ==
true.
为什么没有 get()
方法类似于包含的方法()
有效吗?
How come then there is no get()
method similar to how the contains()
works?
有兴趣知道这个API决定背后的想法
Interested to know the thinking behind this API decision
推荐答案
如果您知道要检索的元素,那么您已经拥有了该元素。在给定元素的情况下,回答 Set
的唯一问题是是否包含()
。
If you know what element you want to retrieve, then you already have the element. The only question for a Set
to answer, given an element, is whether it contains()
it or not.
如果要对元素进行迭代,只需使用 Set.iterator()
。
If you want to iterator over the elements, just use a Set.iterator()
.
听起来你要做的就是为等价类元素指定一个规范元素。您可以使用 Map< MyObject,MyObject>
来执行此操作。请参阅此SO问题或这一个进行讨论。
It sounds like what you're trying to do is designate a canonical element for an equivalence class of elements. You can use a Map<MyObject,MyObject>
to do this. See this SO question or this one for a discussion.
如果您确实要找到一个元素 .equals()
你的原始元素,你必须使用约束 HashSet
,我认为你不得不迭代它并自己检查 equals()
。 API不允许您通过其哈希代码获取内容。所以你可以这样做:
If you are really determined to find an element that .equals()
your original element with the constraint that you MUST use the HashSet
, I think you're stuck with iterating over it and checking equals()
yourself. The API doesn't let you grab something by its hash code. So you could do:
MyObject findIfPresent(MyObject source, HashSet<MyObject> set)
{
if (set.contains(source)) {
for (MyObject obj : set) {
if (obj.equals(source))
return obj;
}
}
return null;
}
蛮力和O(n)丑陋,但如果这是你需要的做...
Brute force and O(n) ugly, but if that's what you need to do...
这篇关于Java:从HashSet中检索元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!