Override equals and hashCode methods (part 2)

Eclipse can generate equals and hashCode methods for any class that has state fields (see post). What if you are writing code outside Eclipse, e.g., using a plain text editor? I usually copy java.lang.String.equals(Object) and modify it:

C:\jdk5> jar xvf src.zip java/lang/String.java
inflated: java/lang/String.java

C:\jdk5> gvim java/lang/String.java
It basically looks like this:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
if (anObject instanceof String) {
xxx anotherString = (xxx)anObject;
//compare the states of two objects
return false;
I then save this template in C:\tmp\equals.txt. Next time I need it inside vim, I just read it into vim with :r /equals.txt.


Anonymous said...

You generally shouldn't use instanceof in an equals() implementation. If the class is final you might get away with it, but generally "A instanceof B" does not imply "B instanceof A".

admin said...

Good point. That explains why the Eclipse-generated equals method doesn't use instanceof. Instead, it uses getClass().

Using instanceof in String.equals()is fine since String is a final class.

Steve Smith said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

J2EE training

online J2EE training

Best Recommended books for Spring framework

Java Interview Questions

Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai