Saturday, October 27, 2007

Java Unboxing and Null

While playing with boxing/unboxing in Java 5, I found an interesting case. If my collection has a null value, the unboxing fails with a NullPointerException at runtime. Here is an example


Set s = new HashSet();
for (int i=0; i < 10; i++) {
s.add(i);
}
s.add(null);

System.out.println("s: " + s);
// this is a problem. The unboxing does not handle null
for (int sx : s) {
System.out.println("sx: " + sx);
}



The output of the progam is here:


s: [2, 4, null, 9, 8, 6, 1, 3, 7, 5, 0]
sx: 2
sx: 4
Exception in thread "main" java.lang.NullPointerException
at com.mykola.TestSets.main(TestSets.java:21)


So, unboxing is fine, unless a collection has a null element.