Friday, April 13, 2007

Java: Object.equals() considered harmful

After years of experience with object-oriented programming and in particular with Java many programmers are too often sure what some piece of code does. Let's have an example:

void m(Collection<Integer> a, Collection<Integer> b) {
a.clear(); b.clear();
a.add(1); b.add(1);

return a.equals(b);
}
This method obviously returns true, because two collections are equal if they have the same elements, right? Wrong!
m(new HashSet<Integer>(), new Vector<Integer>()) ==> false
Welcome, to the wonderful world of subtyping :-(