Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
A boxing conversion converts the value of a primitive type to the corresponding value of the reference type, for instance, from {{int}} to the type {{Integer}} \[[JLS 2005|AA. JavaBibliography#JLS References#JLS 05]\]. 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 example prints {{100}} as the size of the {{HashSet}} while it is expected to print {{1}}. The combination of values of types {{short}} and {{int}} in the operation {{i-1}} leads to autoboxing of the result into an object of type {{Integer}}. (See guideline [EXP05-J. Be aware of integer promotions in binary operators].) The {{HashSet}} contains values of only one type {{Short}} whereas the code attempts to remove objects of the (different) type {{Integer}}. As a result, the remove operation is equivalent to a _No Operation_ (NOP). The compiler enforces type checking so that only {{Short}} values are inserted; however, a programmer is free to remove an object of any type without triggering any exceptions because {{Collections<E>.remove()}} accepts an argument of type {{Object}} and not {{E}}. Such behavior can result in unintended object retention or memory leaks. \[[Techtalk 2007|AA. JavaBibliography#Techtalk References#Techtalk 07]\]

Code Block
bgColor#FFCCCC
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(i - 1);
      }
    System.out.println(s.size());
  }
}

...

Wiki Markup
\[[Core Java 2004|AA. Java References#CoreBibliography#Core Java 04]\] Chapter 5 
\[[JLS 2005|AA. Java References#JLSBibliography#JLS 05]\] Section 5.1.7
\[[Techtalk 2007|AA. Java References#TechtalkBibliography#Techtalk 07]\] "The Joy of Sets"

...

EXP10-J. Avoid side effects in assertions      04. Expressions (EXP)      EXP12-J. Ensure a null pointer is not dereferenced