Java Set,包含,false结果

时间:2014-02-17 16:14:07

标签: java set equals contains compareto

EventObject target = new EventObject("e2");
Set<EventObject> Following = o.getFollowingEvents(e1);
System.out.println("Elements : "+Following.toString());
System.out.println(e2.toString());
System.out.println(Following.toString()+" contains "+e2+" ? = "+Following.contains(target));

打印:

Elements : [e2, e5, end, T]
e2
[e2, e5, end, T] contains e2 ? = false

等于和比较:

@Override
public int compareTo(EventObject o) {
    return this.getName().compareTo(o.getName());
}

@Override 
public boolean equals(Object obj) {
    return (obj instanceof EventObject) && (this.compareTo((EventObject) obj) == 0);
}

如果事件出现在Set?

,这怎么可能呢?

1 个答案:

答案 0 :(得分:11)

听起来你忘了实施hashCode

@Override
public int hashCode() {
    return getName().hashCode(); // Consistent with equals
}

请注意,您不需要在equals方法中执行排序比较 - 您只需要检查名称是否相等。