I have this piece of code:
public void someMethod(String id) {
someOtherMethod(Integer.valueOf(id));
}
public void someOtherMethod(int id) {
// do something with id
}
And on that second line, Findbugs is throwing this exception:
Boxing/unboxing to parse a primitive
Why is Findbugs complaining about this when I'm simply calling Integer.valueOf() / how can I fix this?
The issue is that Integer.valueOf
returns an Integer
, not an int
, but your someOtherMethod
expects an int
. Findbugs is basically warning you that you're doing it a long-winded way that involves potentially creating an object (the Integer
) that you don't need which you're then immediately going to unbox by passing it to someOtherMethod(int)
, e.g.:
String => int => Integer => int ^^^^^^^^^^^^^^ \--- This is inside Integer.valueOf
Instead, you can and probably should avoid that unnecessary round-trip through Integer
and simply do:
String => int ^^^^^^^^^^^^^ \--- Integer.parseInt
There's just no need for the temporary Integer
and the potential memory allocation and such surrounding it.
If someOtherMethod
were expecting an Integer
, you wouldn't get the warning, because the Integer
isn't purely temporary.
This is just one of a class of unnecessary-boxing-conversions that Findbugs and tools like it helpfully point out.