Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 912
bn. Avatar asked Apr 27 '14 00:04

bn.


2 Answers

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.

like image 145
Jeffrey Avatar answered Oct 05 '22 02:10

Jeffrey


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().

like image 35
user3577291 Avatar answered Oct 05 '22 02:10

user3577291