JDK-6341875 : New for loop should treat null as an empty list
  • Type: Enhancement
  • Component: specification
  • Sub-Component: language
  • Affected Version: 5.0
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: linux
  • CPU: x86
  • Submitted: 2005-10-26
  • Updated: 2020-04-27
  • Resolved: 2006-11-02
Related Reports
Relates :  
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
The new for loop construct in Java 5 is great, but many people have quickly realized that one helpful enhancement would be to have the for loop check for a null collection or array and quietly skip the loop if it finds one.  For example, instead of this:
  List<Strings> list;
  // ...
  if (list!=null) {
    for (String s: list) {
      System.out.println(s);
    }
  }

Do this:
  for (String s: list) { // if list==null, then skip over the list as though it was empty
    System.out.println(s);
  }


JUSTIFICATION :
The syntax is already in place to handle this.  It would just avoid having to wrap so many for loops with a check for null first, which would make code more readable.  The semantics also already make sense, i.e., if we read these for loops as "for each thing in this list, do that", then it makes sense that if the list is either empty OR NULL, then there is nothing in it, so nothing should be done.  The CPU cost of one extra comparison at the beginning of the for loop to check for null is probably neglegible.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
The following code should quietly print nothing instead of throwing a NullPointerException:

String[] names = null;
for (String name: names) {
  System.out.println(name);
}
ACTUAL -
Currently a NullPointerException is thrown when trying to iterate over a null array or collection.

---------- BEGIN SOURCE ----------
List<String> list = new ArrayList<String>();

String[] names = null;
for (String name: names) {
  list.add(name);
}
assertEquals(0, list.size());

names = new String[] {"a", "b", "c"};
for (String name: names) {
  list.add(name);
}
assertEquals(3, list.size());
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
Check for null first, i.e.,

if (names!=null) {
  for (String name: names) {
    list.add(name);
  }
}

Comments
EVALUATION This makes everyone pay the cost of the null check, even though most people don't want it. And if you'd get a NullPointerException from the basic for loop, you should get one with the enhanced for loop; it's just syntactic sugar. Implicitly hiding NullPointerExceptions is a Bad Idea.
02-11-2006