Re: Unique Long for Map
"caultonpos@gmail.com" <caultonpos@gmail.com> writes:
I have a common need to keep a small cache of values which are often
identified by two or more long values.
e.g. (1,2) ---- > "Abc"
(1,9) -----> "Def"
For performance I like using a hashtable but to use it I do this:
public void addToCache(Long nbr1, Long nbr2, String value) {
StringBuffer sb = new StringBuffer(32);
sb.append(nbr1);
sb.append(":");
sb.append(nbr2);
hashtable.put (sb.toString(), value);
}
or something similar to that. The point is to make the key unique I
create a String.
That could be overkill. Also, comparing strings (of up to 41 chars) is
slower than comparing two longs.
I would imagine lookups would be more efficient if
the key was not a String but a number. But how to make a unique
number from these two. Perhaps if I knew both numbers would be less
than a billion then (nbr1 * 1,000,000,00 + nbr2) but that seems a
little clunky.
It is. It will break if the limit rises to 10 billion. Arbitrary limits
are ... well, arbitrary.
Is there a well defined method to create a single unique number based
upon two values?
Don't create a number, just create an object containing those longs:
public class TableKey {
public final long l1; // or make it private and add a getLongValue1();
public final long l2;
public TableKey(long l1, long l2) {
this.l1 = l1;
this.l2 = l2;
}
public boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof TableKey)) { return false; }
TableKey other = (TableKey) o;
return l1 == other.l1 && l2 == other.l2;
}
public int hashCode() {
return (int) (l1 ^ (l1 >> 32)) * 31 + (l2 ^ (l2 >> 32)); // or something
}
}
Not tested.
Good luck
/L
--
Lasse Reichstein Nielsen - lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'