Java Set, contains, false result

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));

Print :

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

Equals and CompareTo :

@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);
}

How is this possible, if the event is present on the Set ?

Jon Skeet
people
quotationmark

It sounds like you've just forgotten to implement hashCode:

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

Note that you don't really need to perform an ordering comparison in your equals method - you just need to check whether or not the names are equal.

people

See more on this question at Stackoverflow