...
The language's type checking guarantees that only values of type Short
can be inserted into the HashSet
. Nevertheless, programmers are free to attempt to remove an object of any type because Collections<E>.remove()
accepts an argument of type Object
rather than of type E
. Such behavior can result in unintended object retention or memory leaks [Techtalk 2007].
Compliant Solution
Objects removed from a collection must share the type of the elements of the collection. Numeric promotion and autoboxing can produce unexpected object types. This compliant solution uses an explicit cast to short
that matches the intended boxed type.
...