Versions Compared

Key

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

...

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}}, rather than {{Short}}. (See guideline [INT10-J. Be aware of integer promotion behavior].) 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)accomplishes nothing. The compiler enforces type checking so that only {{Short}} values are inserted;.  howeverHowever, 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. Bibliography#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<100i < 100; i++) {
        s.add(i);
        s.remove(i - 1);
      }
    System.out.println(s.size());
  }
}

...

Objects removed from a collection should always share the type of the elements of the collection. Numeric promotion and autoboxing can produce unexpected object types. Ensure expected operation by using explicit casts to primitive types that parallel This compliant solution uses an explicit cast to short that parallels the intended boxed typestype.

Code Block
bgColor#CCCCFF
public class ShortSet {
  public static void main(String[] args) {
    HashSet<Short> s = new HashSet<Short>();
      for(short i = 0; i<100i < 100; i++) {
        s.add(i);
        s.remove((short)(i - 1)); // cast to short 
      }
    System.out.println(s.size());
  }
}

...