What is the appropriate way to handle warning: "The expression of type x is boxed into x"
Asked Answered
P

2

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.

Popularly answered 27/4, 2014 at 0:0 Comment(1)
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.Pelisse
T
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.

Tetraspore answered 27/4, 2014 at 0:3 Comment(3)
Manual unboxing has one advantage though : explicit dereferencing of a potentially null pointer.Coterminous
@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.Tetraspore
@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.Coterminous
H
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().

Hezekiah answered 27/4, 2014 at 0:30 Comment(1)
@Popularly 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. 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.Walterwalters

© 2022 - 2024 — McMap. All rights reserved.