Java News from Tuesday, March 16, 2004

I noticed something bothersome about atouboxing and unboxing in Java 1.5 in Paul Tyma'a Java 1.5 tutorial at SD West today. Equality is not longer transitive! Here's how it works:

Integer a = new Integer(7);
int b = 7;
Integer c = new Integer(7);
if (a == b) System.out.println("a = b");
else System.out.println("a != b");
if (b == c) System.out.println("b = c");
else System.out.println("b != c");
if (c == a) System.out.println("c = a");
else System.out.println("c != a");

It appears that the result of this will be:

a = b
b = c
c != a

I haven't compiled this yet because I'm typing this from a Mac OS X laptop in the classroom, which doesn't support Java 1.5 yet; but the results Paul showed indicate this will happen. In other words equality is no longer transitive! This bothers me immensely. It seems that it bothers someone at Sun as well. The documentation fo the equals method in Java 1.4.2 says, the equals() method "is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true." That applies to the equals(), method not the == operator. However, I really think == should be transitive too.

On the positive side, Paul's convinced me that most of the syntax of autoboxing and unboxing is a win. His example of using an int as a key in a Hashtable is compelling, and I really like being able to use Number objects in regular code.