开发者

Java: Retrieving object from the set just by computing its hashcode

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 long has 264 possible values; an int only 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 floatToIntBits to compute the hash code to start with. Look at what Long.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 a Map...


You can generate a static class (eg:Utility), and create a method which can generate unique hash in it.But you must estimate that there are how many objects will be created in possible, and then create a algorithm to generate the unique to distinguish the objects. And also the hashcode method of the Event class should be overrided because you overided the equals method.

And use the map :

Map id2event = new HashMap();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜