Autoboxing In Java & Bug Patterns

Consider the following example:

1) Some Java Bean:

public class SomeBean implements Serializable {
private int someInt;

public int getSomeInt() {
return this.someInt;

public void setSomeInt(int someInt) {
this.someInt = someInt;

2) And somewhere in some class (with business logic), you have this:

HashMap<String, Integer> someMap = new HashMap<String, Integer>();

...and somewhere down the line, you find a code statement like this:


The above code statement works fine, when there are no 'null' values. But if there is a null value for some key, it fails.....because 'AutoBoxing' throws a NullPointerException when the above code statement tries to unbox a 'null' value.

So, the immediate solution for that would be something like:

Integer someInt = someMap.get("someString");

someBeam.setSomeInt((someInt != null) ? someInt : 0);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.