Re: Is auto(un)boxing good style?



Patricia Shanahan wrote:
Here is a sample program that uses auto-boxing and auto-unboxing:

public class AutoBoxQuestion {
public static void main(String[] args) {
/* This does seem better than writing out
{new Long(1), new Long(2), new Long(3), new Long(4)}*/
Long[] data = new Long[]{1L,2L,3L,4L};

You don't want to be using new Long. FindBugs will flag it as being inefficient compared to Long.valueOf.

long[] would be better. It's a shame Java has primitives. OTOH, if it didn't have primitives (and didn't introduce the idea of non-nullability), pretty much any expression involving a long could NPE.

long total = 0;
for(Long val: data){
// Or should this be val.getLong()?
total += val;

It shouldn't be using getLong, no. (longValue is more likely).

}
System.out.println("Total is "+total);
}
}


Is it good style to depend on the auto-boxing and auto-unboxing?

It's not a feature I'm particularly keen on, but it is part of the language now. You should be able to expect that other programmers know about it, and no to be careful about introducing possible NPEs. It's now a commonly used part of the language - not to use it (in obvious situations) would be unidiomatic.

Why would you be worried about mixing up long and Long?
* Might use == to compare values, but actually compare references.
* Might use == to compare references, but actually compare values.
* NPEs, if the value could be null.
* Potential performance impact.

Honestly, I don't think any of those are, in practice, big issues.

There is one significant advantage auto-unboxing has over manual-unboxing: No casting goes on. Long gets unboxed to long, and the compiler will complain if you assign that to an int. Have somewhere buried in your code .intValue, and even if you assign it to a long the value will be quietly truncated. Fixed length integers should have died twenty years ago.

Tom Hawtin
.