我见过其他关于基于索引值从Set
获取对象的问题,我理解为什么这是不可能的,但我没有找到一个很好的解释为什么get by object是不允许的,所以我想我会问。
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)
就足够了)?
发布于 2012-12-13 23:58:09
你的最后一句话是答案。
get(Object o)
将遍历HashSet
,查找与o
相等的另一个对象(使用equals(o)
方法)。所以它确实和contains(o)
是一样的,只是返回的结果不一样。
发布于 2012-12-13 23:59:35
如果您想知道set
中已经存在new Foo("1");
对象,则需要使用contains
方法,如下所示:
boolean present = set.contains(new Foo("1"));
不支持get
类型的方法,即set.get(new Foo("1"));
,因为它没有意义。您已经拥有了对象,即new Foo("1")
,那么您将通过get
方法查看哪些额外信息。
发布于 2014-07-20 00:41:31
HashSet比HashMap简单一点。如果你不需要HashMap的特性,为什么还要使用它呢?如果像getObject(ObjectType o)这样的方法是由Java语言实现的,那么在调用contain()方法之后,我们就不需要遍历集合了……
https://stackoverflow.com/questions/13863506
复制相似问题