I need help creating an equals method.
The method is: boolean equals(Zombie other)
The description specifically says: "Accepts another Zombie object as an argument and returns true if the zombie has the same name and same degree of infection, weapon(s) and brains as the other Zombie."
I do not understand how I would separate the Zombie other to separate parts to compare to the instance variables then how I would compare all the pieces.
Add a comment |
1 Answer
This would be correct implementation of equals() in your case.
@Override public boolean equals(Object obj) { if (obj instanceof Zombie){ Zombie zombiObj= (Zombie) obj; if(zombiObj.getName().equals(this.getName()) && zombiObj.getInfection().equals(this.getInfection())&& zombiObj.getWeapon().equals(this.getWeapon()) && zombiObj.getBrain()== this.getBrain() ) { return true; }else{ return false; } } else{ return false; } } 10 Comments
Dark Knight
@JessNicole27 , hope this solves your problem..
JessNicole27
It did but all for one part, she wants us to compare the brains as well and it is an integer. jGrasp said I cant deference that so how would I do that
Dark Knight
Refer to updated post, added brain equality condition for type as int.
isnot2bad
Please note that you also have to override hashCode if you override equals! (Two objects that are equal according to equals() must return the same hashCode)
Dark Knight
@isnot2bad : here we are comparing objects using it's contents. Here HashMap/ Map is not used. And hence implementing hashCode() here is not mandatory. Please correct me if i misunderstood your comment.
|