Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

java - Findbugs issue with "Boxing/unboxing to parse a primitive" with Integer.valueOf(String)

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?

question from:https://stackoverflow.com/questions/32516893/findbugs-issue-with-boxing-unboxing-to-parse-a-primitive-with-integer-valueof

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...