Autoboxing in Java and equal

von

Today I was preparing some slides for my upcoming SCJP training. I stumbled across something really odd in Java. Lets say you have this code:

{
  Integer i3 = 10;
  Integer i4 = 10;
  test(i3, i4);
}
{
  Integer i3 = new Integer(10);
  Integer i4 = new Integer(10);
  test(i3,i4);
}

public static void test(Integer i3, Integer i4) {
  if(i3 == i4) System.out.println("==");
  if(i3.equals(i4)) System.out.println("meaningfully equal");
  if(i3 != i4) System.out.println("not ==");
}

It has been said, due to the autoboxing feature of Java >5 Wrapper-classes can be compared with ==, because they are unboxed and compared. Output for number one is:

==
meaningfully equal

You would guess option two prints out the same, but it does not. The output is:

meaningfully equal
not ==

Since you have assigned objects yourself, they are not ==. Only when you let the JVM instance the Wrapper with autoboxing, this feature works.

Isn’t this very unrealiable? You cannot trust Integer == Integer to work in all cases. The developer must follow strict conventions. Nasty, nasty…

equals for comparing Object and == for primitives is still the best solution.

Tags: #Java #Training

Newsletter

ABMELDEN