Sunday, October 05, 2008

How to find first and last entry of HashMap

http://forums.sun.com/thread.jspa?threadID=403658&tstart=81825
How come Hashtable / HashMap have search order constant . ?
/**
* The table, resized as necessary. Length MUST Always be a power of two.
*/
transient Entry[] table;
// and here's the method that intrests you
public Object get(Object key) {
Object k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
Entry e = table[i];
while (true) {
if (e == null)
return e;
if (e.hash == hash && eq(k, e.key))
return e.value;
e = e.next;
}
}
so, as you see, if you have one Entry per bucket, then it's as easy as taking from an array, but if you have more that one entries in one bucket, then it has to loop that while for a while.

No comments: