In java for a comparison in an if statement, I wrote
if (x == 1)
and got a comment in code review to use NumberUtils.INTEGER_ONE instead of 1. I was wondering what benefit does it actually add to the code.
NumberUtils.INTEGER_ONE
comes probably from commons-lang.
In commons-lang
, it is defined as :
public static final Integer INTEGER_ONE = new Integer(1);
In commons-lang3
, it is defined as :
public static final Integer INTEGER_ONE = Integer.valueOf(1);
The first version doesn't use the internal integer cache (as didn't exist yet)
while the second version takes advantage of it.
Now, whatever the version you are using, it doesn't really matter for your question as you compare integer values and you don't assign or create integer value (case where the cache could make more sense).
Suppose you are using it in this way :
if (x == NumberUtils.INTEGER_ONE)
If x
is a primitive, it is not very efficient as it will produce an unboxing operation to convert NumberUtils.INTEGER_ONE
to a 1
int primitive.
If x
is an object, it is not a good idea either as Integer
objects should be compared with equals()
or intValue()
.