Versions Compared

Key

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

...

Code Block
bgColor#FFcccc
public static int cardinality(Object obj, final Collection col) {
  int count = 0;
  Iterator it = col.iterator();
  while(it.hasNext()) {
    Object elt = it.next();
    if((null == obj && null == elt) || obj.equals(elt)) {  // null pointer dereference
      count++;
    }
  }
  return count;
}

Compliant Solution

The straightforward solution to this issue is to decouple the null checks from the expression that invokes a method on the variable objThis compliant solution eliminates the null pointer dereference.

Code Block
bgColor#ccccff
ifpublic static int cardinality(Object obj, == nullfinal Collection col) {
  for(int count = 0;
  Iterator it = col.iterator();
  while(it.hasNext();) {
 //  col isObject currentlyelt named coll= it.next();
    if (it.next()null == null) {
      count++;
    }
  }
} else {
  for (Iterator it = col.iterator();it.hasNext();) { // col is currently named coll
    if (obj.equals(it.next(obj && null == elt) || 
        (null != obj && obj.equals(elt))) {
      count++;
    }
  }
  return count;
}

Wiki Markup
Null pointer dereferences can happen in many path dependent ways. Because of the limitations of automatic detection tools, code review and manual inspection of code are indispensable activities \[[Hovemeyer 07|AA. Java References#Hovemeyer 07]\]. Annotations for method parameters that must be non-null can also alleviate the problem to a certain extent by aiding automatic detection.  

...