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


i have created event class. can see, both hashcode , equals methods use 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 store objects of class in hashset collection.

set<event> events = new hashset<event>(); 

since hash computation field of type long i'd retrieve elements events hashset computing hash of id. e.g.:

events.get(3); 

is possible or should use hashmap it:

map<long, event> id2event = new hashmap<long, event>(); 

?

you should absolutely not rely on hash code uniqueness. long has 264 possible values; int has 232. therefore hash collisions entirely possible. don't use hash codes sole equality test. that's not they're designed for.

hash codes designed key set of potential matches, checked more rigorously normal equality.

(as aside, don't think it's great idea use floattointbits compute hash code start with. @ long.hashcode() does.)

edit: of course, if did want rely on that, hashset<e> doesn't expose method getting element hash code, precisely because it's bad idea in cases... if want mapping, create map...


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -