Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider Java v3.0

...

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 [EXP08-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>Collections&lt;E&gt;.remove()}} accepts an argument of type {{Object}} and not {{E}}. Such behavior can result in unintended object retention or memory leaks. \[[Techtalk 07|AA. Java References#Techtalk 07]\]

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

...

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

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[Core Java 04|AA. Java References#Core Java 04]\] Chapter 5 
\[[JLS 05|AA. Java References#JLS 05]\] Section 5.1.7
\[[Techtalk 07|AA. Java References#Techtalk 07]\] "&quot;The Joy of Sets"&quot;

...

EXP04-J. Be wary of invisible implicit casts when using compound assignment operators      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;04. Expressions (EXP)      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;EXP06-J. Be aware of the short-circuit behavior of the conditional AND and OR operators