Overriding the java equals() method quirk -


i ran interesting (and frustrating) issue equals() method today caused thought tested class crash , cause bug took me long time track down.

just completeness, wasn't using ide or debugger - old fashioned text editor , system.out's. time limited , school project.

anyhow -

i developing basic shopping cart contain arraylist of book objects. in order implement addbook(), removebook(), , hasbook() methods of cart, wanted check if book existed in cart. off go -

public boolean equals(book b) {     ... // more code here - null checks     if (b.getid() == this.getid()) return true;     else return false; } 

all works fine in testing. create 6 objects , fill them data. many adds, removes, has() operations on cart , works fine. read can either have equals(type var) or equals(object o) { (cast) var } assumed since working, didn't matter much.

then ran problem - needed create book object id in within book class. no other data entered it. following:

public boolean hasbook(int i) {     book b = new book(i);     return hasbook(b); }  public boolean hasbook(book b) {     // .. more code here     return this.books.contains(b); } 

all of sudden, equals(book b) method no longer works. took long time track down without debugger , assuming cart class tested , correct. after swaapping equals() method following:

public boolean equals(object o) {     book b = (book) o;     ... // rest goes here    } 

everything began work again. there reason method decided not take book parameter though book object? difference seemed instantiated within same class, , filled 1 data member. i'm very confused. please, shed light?

in java, equals() method inherited object is:

public boolean equals(object other); 

in other words, parameter must of type object.

the arraylist uses correct equals method, calling 1 didn't override object's equals.

not overriding method correctly can cause problems.

i override equals following everytime:

@override public boolean equals(object other){     if (other == null) return false;     if (other == this) return true;     if (!(other instanceof myclass))return false;     myclass othermyclass = (myclass)other;     ...test other properties here... } 

the use of @override annotation can ton silly mistakes.

use whenever think overriding super class' or interface's method. way, if wrong compile error.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -