【发布时间】:2011-07-01 08:31:01
【问题描述】:
我已经创建了 Event 类。如您所见,hashCode 和 equals 方法都只使用 long 类型的 id 字段。
public class Event {
private long id;
private Map<String, Integer> terms2frequency;
private float vectorLength;
@Override
public long hashCode() {
return this.id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Event other = (Event) obj;
if (id != other.id)
return false;
return true;
}
我会将这个类的对象存储在 HashSet 集合中。
Set<Event> events = new HashSet<Event>();
由于只有 long 类型的字段用于散列计算,我想通过计算 id 的散列从事件散列集中检索元素。例如:
events.get(3);
是否有可能或者我应该使用 hashMap:
Map<Long, Event> id2event = new HashMap<Long, Event>();
?
【问题讨论】:
-
有很多奇怪的事情:
getClass() != obj.getClass(),但你转换为SimpleEvent而不是Event。Float.floatToIntBits()上的long也很奇怪。hashCode公式也没有多大意义(只是加 31?) -
使用
if (Float.floatToIntBits(id) != Float.floatToIntBits(other.id))和if (id != other.id)不一样吗? -
@Thomas Mueller 正确的评论。这是由于类的先前名称和其中变量的类型而发生的。我在更改类名和变量类型时没有注意到。