15

I'm not looking to to turn off or ignore the warning as in The expression of type x is boxed into X?.

I'd like to know what the correct way to handle/avoid this warning is if one was so inclined.

Community
  • 1
  • 1
bn.
  • 7,739
  • 7
  • 39
  • 54
  • I tend to agree with Jeffrey about "turn off the warning". Eclipse lists this warning under "Potential programming problems", according to the link you included; but I don't see it as a source of problems. – ajb Apr 27 '14 at 00:08

2 Answers2

16

Boxing and unboxing are operations you can do by hand, but they're build into the language to avoid the repetition you will undoubtedly encounter.

Integer obj = Integer.valueOf(5); // instead of Integer obj = 5;
int i = obj.intValue(); // instead of int i = obj;

In my opinion, the appropriate way to handle that warning to turn it off. But if that is not an option, you can do the above.

Jeffrey
  • 44,417
  • 8
  • 90
  • 141
  • 2
    Manual unboxing has one advantage though : explicit dereferencing of a potentially null pointer. – KeatsPeeks Apr 27 '14 at 00:07
  • @Keats It's not much of an advantage. Either way, if `obj` was `null`, you are going to get a `NullPointerException`. I guess in this case it's a bit more obvious where it's coming from. – Jeffrey Apr 27 '14 at 00:10
  • 4
    @Jeffery What I mean is that with automatic unboxing, you might forget about the possible NPE, while doing it manually forces you to think a about it. That's the purpose of the OP warning : still forcing you to think about the NPE even if you're using automatic unboxing. – KeatsPeeks Apr 27 '14 at 10:49
6

In my opinion its better to explicitly box-unbox the values as it makes the code more readable. Also there might be subtle differences when we use different approaches to boxing. For eg,

Integer i = new Integer(1);

Integer j = Integer.valueOf(1);

According to javadoc Integer.valueOf() caches objects so i==j will return false.

Also another way to explicitly box a primitive to Integer is

Integer k = (Integer)1; but this actually calls Integer.valueOf().

NoobEditor
  • 15,563
  • 19
  • 81
  • 112
user3577291
  • 101
  • 2
  • 1
    @bn. I agree with this answer, in my opinion it is better to explicitly box-unbox. In addition to making the code more clear, it makes sure you never run into problems like the ones mentioned in the link in [this answer](http://stackoverflow.com/a/19512862/2814308). Whether the likelihood of those problems is small or not is not too important for me because the price to pay to obtain this certainty (explicitly boxing-unboxing) is extremely low. – SantiBailors Apr 15 '15 at 09:46