Long.valueOf(long) : strang implementation
See Long.valueOf(long) impl :
publicstatic Long valueOf(long l){
finalint offset = 128;
if (l >= -128 && l <= 127){// will cache
return LongCache.cache[(int)l + offset];
}
returnnew Long(l);
}
Looking over javadoc for this method, you infer that when Long is used, it is mainly for small values, so they should be cached. WTF ?! How did they find a statistical results for Long usage ? As I'm using Long mainly for counter going over int limits or for timestamp, I'm doubtful.
Does anyone know about it ?
[1052 byte] By [
Kilwcha] at [2007-11-27 8:18:37]

It easy to answer without executing code now I have post the source code of Long.valueOf(long), but just try to guess the result of each sysout :
Long a = new Long(2);
Long b = new Long(2);
System.out.println(a == b);
Long a1 = 2;
Long b1 = 2;
System.out.println(a1 == b1);
Long a2 = Long.valueOf(2);
Long b2 = Long.valueOf(2);
System.out.println(a2 == b2);
Long a3 = Long.valueOf(256);
Long b3 = Long.valueOf(256);
System.out.println(a3 == b3);
Long a4 = 256;
Long b4 = 256;
System.out.println(a4 == b4);
> It easy to answer without executing code now I have
> post the source code of Long.valueOf(long), but just
> try to guess the result of each sysout :
Welcome to the joys of auto-boxing. Which was why Foo.valueOf(foo) was introduced. It does make sense (of a sort) for Integer and smaller sizes, probably not so much for Long.
Your example code becomes much more "fun" if you explicitly make use of auto-boxing:
public static void main(String[] args)
{
Long a1 = 2;
Long a2 = 2;
System.out.println(a1 == a2);
Long b1 = 2345;
Long b2 = 2345;
System.out.println(b1 == b2);
System.out.println(b1 <= b2);
long c1 = 2345;
Long c2 = 2345;
System.out.println(c1 == c2);
}
Longs aren't used that extensively anyway, but when they are they'll still be low most of the time, long just gives them room to grow.
My guess it that the two commonest values of long are 0 and -1, with +1 a runner up.
It's like in maths, the only two integers that really exist are 0 and 1, all else is the result of limited sampling ;-)