views:

164

answers:

3

Is there any justifiable reason to in Java something like

Long l = new Long(SOME_CONSTANT)

This creates an extra object and is tagged by FindBugs, and is obviously a bad practice. My question is whether there is ever a good reason to do so?

I previously asked this about String constructors and got a good answer, but that answer doesn't seem to apply to numbers.

+5  A: 

Only if you want to make sure you get a unique instance, so practically never.

Some numbers can be cached when autoboxed (although Longs aren't guaranteed to be), which might cause problems. But any code that would break because of caching probably has deeper issues. Right now, I can't think of a single valid case for it.

Michael Myers
+1  A: 

The only thing I can think of is to make the boxing explicit, although the equivalent autoboxed code is actually compiled into Long.valueOf(SOME_CONSTANT) which can cache small values : (from jvm src)

   public static Long valueOf(long l) {
    final int offset = 128;
    if (l >= -128 && l <= 127) { // will cache
        return LongCache.cache[(int)l + offset];
    }
        return new Long(l);
  }

. Not a big deal, but I dislike seeing code that continually boxes and unboxes without regard for type, which can get sloppy.

Functionally, though, I can't see a difference one way or the other. The new long will still compute as equals and hashcode equals to the autoboxed one, so I can't see how you could even make a functional distinction if you wanted to.

Steve B.
+4  A: 

My question is whether there is ever a good reason to do so?

You might still use it if you want to write code compatible with older JREs. valueOf(long) was only introduced in Java 1.5, so in Java 1.4 and before the constructor was the only way to go directly from a long to a Long. I expect it isn't deprecated because the constructor is still used internally.

McDowell
That is indeed a good reason (although, what percentage of Java apps are still on 1.4 or below?).
Michael Myers
Old platforms can live for a long time, especially in the enterprise. When Java 6 came out, I was targeting a Java 1.3 platform.
McDowell
I wasn't aware of that. I was wondering why I was seeing it in legacy code.
Uri
Agree. The default Java on our IBM platform is Java 1.4. You will have to take my word for it that it can be very cumbersome to have a non-default Java installed, and that it is very often easier just to have your code 1.4 compatible.
Thorbjørn Ravn Andersen