【发布时间】:2012-12-01 13:24:48
【问题描述】:
我已经看到其他关于根据索引值从Set 获取对象的问题,我理解为什么这是不可能的。但是我无法找到一个很好的解释来解释为什么不允许通过对象获取,所以我想我会问。
HashSet 由HashMap 支持,因此从中获取对象应该非常简单。就像现在一样,看来我必须遍历 HashSet 中的每个项目并测试似乎没有必要的相等性。
我可以只使用Map,但我不需要键:值对,我只需要Set。
例如说我有Foo.java:
package example;
import java.io.Serializable;
public class Foo implements Serializable {
String _id;
String _description;
public Foo(String id){
this._id = id
}
public void setDescription(String description){
this._description = description;
}
public String getDescription(){
return this._description;
}
public boolean equals(Object obj) {
//equals code, checks if id's are equal
}
public int hashCode() {
//hash code calculation
}
}
和Example.java:
package example;
import java.util.HashSet;
public class Example {
public static void main(String[] args){
HashSet<Foo> set = new HashSet<Foo>();
Foo foo1 = new Foo("1");
foo1.setDescription("Number 1");
set.add(foo1);
set.add(new Foo("2"));
//I want to get the object stored in the Set, so I construct a object that is 'equal' to the one I want.
Foo theFoo = set.get(new Foo("1")); //Is there a reason this is not allowed?
System.out.println(theFoo.getDescription); //Should print Number 1
}
}
是否因为 equals 方法旨在测试“绝对”相等而不是“逻辑”相等(在这种情况下contains(Object o) 就足够了)?
【问题讨论】:
-
如果你想要索引,你有列表。 HashSet 不能保证插入顺序,所以 get 方法没有意义。您缺少的是实现
equals并使用contains()它将迭代并找到对象。 -
@assylias 这与我所询问的情况非常接近。但是,我不喜欢包含第三方库的答案。
-
在 HashSet 中它几乎就在那里...
set.contains代表map.contains,它确实:return getEntry(key) != null;其中getEntry(key).getKey();是您要寻找的...不知道为什么会这样不包括在内... -
诚然,HashMap 也没有提供这样的方法……