Monday, November 09, 2009

Java: Forgetting to override .equals()

This one always catches me out. I have a bunch of icons in my program, all extending the Rectangle class (seems like common sense to me). However, I don't actually fill in the dimensions until I've got the full list of icons (stored in an ArrayList()) so they are all zero-sized rectangles.

Before I add each icon to this list, I check whether it's already there:-

public void addIcon(Icon icon) {
if (iconlist.contains(icon) == false) {

Have you spotted the problem? Since the dimensions for the icons are all zero, and the contains() function uses the equals() method of the icon class, then once one icon is added to the list no others will be. This is because the Icon/Rectangle class' equals() method compares the dimensions, and thus all my icons are actually equal, so it thinks that the icon list already contains the said icon. (That all seems very verbose for what is quite a simple problem).

Note to self: Always override the equals() method.

No comments: