Sunday, February 6, 2011

Autoboxing puzzler

While performing code review I came across the following code (simplified for this post)

private void box(Long l) {
 if (l.equals(1)) {
  System.out.println("eq");
 }
 else {
  System.out.println("not eq");
 }
}

What will be printed when we call box(new Long(1))?
Can you spot the bug?

The condition l.equals(1) will always evaluate to false.

This happens due to the autoboxing specification and the implementation of the Long.equals() method.
According to the specification if the primitive value (1 in this case) is an int it is converted to a reference of class Integer.
The Long.equals() method starts with type comparison using the instanceof operator, which returns false for an instance of type Integer.

A possible solution is to compare the value to a reference of class Long value using if (l.equals(1L)), which boxes the value 1L to a Long.

No comments:

Post a Comment