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

StackOverflow https://stackoverflow.com/questions/23317876

  •  10-07-2023
  •  | 
  •  

Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top