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.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With