2

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.

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

4 Comments

That is indeed a good reason (although, what percentage of Java apps are still on 1.4 or below?).
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.
I wasn't aware of that. I was wondering why I was seeing it in legacy code.
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.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.