我见过其他关于基于索引值从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)
就足够了)?
https://stackoverflow.com/questions/13863506
复制相似问题