I have created the Event class. As you can see, both hashCode and equals methods use only the id field of type long.
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;
}
I will store the objects of this class in the HashSet Collection.
Set<Event> events = new HashSet<Event>();
Since for the hash computation only the field of the type long I’d like to retrieve the elements from the events hashset by computing the hash of the id. E.g.:
events.get(3);
Is it possible or should I use the hashMap for it:
Map<Long, Event> id2event = new HashMap<Long, Event>();
?
You should absolutely not rely on hash code uniqueness. A
longhas 264 possible values; anintonly has 232. Therefore hash collisions are entirely possible. Don’t use hash codes as your sole equality test. That’s not what they’re designed for.Hash codes are designed to quickly get from a key to a set of potential matches, which are then checked more rigorously with normal equality.
(As an aside, I don’t think it’s a great idea to use
floatToIntBitsto compute the hash code to start with. Look at whatLong.hashCode()does.)EDIT: Of course, even if you did want to rely on that,
HashSet<E>doesn’t expose a method for getting an element by its hash code, precisely because it’s a really bad idea in almost all cases… if you want a mapping, create aMap…