While cleaning up in the core classes of Trekwar yesterday (documenting functions, formatting/structuring code, minor improvements) I also saw lots of equals(Object o) methods. And in my infinite wisdom I decided to use generics since it is used pretty extensively throughout the code anyway, so I changed basically all the equals methods.
example:
public boolean equals(Object o) {
if(o instanceof Structure)
return equals((Structure)o);
return false;
}
changed to:
public boolean equals(Structure s2) {
return name.equals(s2.getName());
}
Now this is not a problem when writing code, as you pretty much always compare objects of the same type. However, the code also uses the Java Collections contains() method a few places, and it always uses the equals(Object) version. So when my classes no longer provided this method, the default one inherited from java.lang.Object was used instead. This caused a strange array of bugs to appear (star systems on the map not shown with faction color/icon except for the Cardassians for some strange reason, users not having any technologies, unable to build any structures, generally erratic behavior, etc..). Luckily I discovered the cause pretty quickly and only wasted about an hour or so on this :)
I guess the lesson is that objects that needs to be compared, directly or indirectly by contains() or other methods, should always define an equals(Object) method that just passes the call along to the equals method written with generics.
public boolean equals(Object o) {
if(o instanceof Structure) {
return equals((Structure)o);
}
return false;
}
And perhaps that you should not mess around with your code for hours on end without stopping to test if you broke it once in a while :)