Wiki Markup |
---|
A Boxingboxing conversion converts the valuesvalue of a primitive type to the corresponding valuesvalue of the reference type, for instance, from {{int}} to the type {{Integer}} \[[JLS 5.1.7 Boxing Conversion|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7]\]. It can be convenient in many cases where an object parameter is desired, such as with collection classes like {{Map}} and {{List}}. Another use case is to pass object references to methods, as opposed to primitive types that are always passed by value. The resulting wrapper types also help reduce clutter in code. |
...
Wiki Markup |
---|
This noncompliant code snippet \[[Techtalk 07|AA. Java References#Techtalk 07]\] prints {{100}} as the size of the {{HashSet}} while it is expected to print {{1}}. The combination of values of atypes {{short}} and an {{integerint}} value in the operation {{i-1}} leads to autoboxing into an object of type {{Integer}} object. The {{HashSet}} contains only values of type {{shortShort}} values whereas (distinctly typed) whereas the code attempts to remove objects of the (different) type {{Integer}}. objectsAs area being removed successively. The result, the remove operation is as a result equivalent to a _No Operation_ (NOP). The compiler enforces type checking so that only {{shortShort}} values are inserted, however, a programmer is free to remove an object of any type without triggering any exceptions since {{Collections<E>.remove()}} takes an Object a parameter of type {{Object}} and not a parameter andof nottype {{E}}. Such behavior can result in unintended object retention or memory leaks. |
...
Compliant Solution
Avoid mixing the different boxed integer types together with an integer
type. If inevitable, cast the autoboxed Integer
object to a Short
to . To remedy the issue described in the noncompliant code, if an arithmetic operation is going to produce a primitive type which will be autoboxed to the wrong type, cast the primitive type correctly before allowing the autoboxing to work.
Code Block | ||
---|---|---|
| ||
public class ShortSet { public static void main(String[] args) { HashSet<Short> s = new HashSet<Short>(); for(short i=0; i<100;i++) { s.add(i); s.remove((short)(i-1)); //cast to short } System.out.println(s.size()); } } |
...