2

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.

0

1 Answer 1

3

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; } } 
Sign up to request clarification or add additional context in comments.

10 Comments

@JessNicole27 , hope this solves your problem..
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
Refer to updated post, added brain equality condition for type as int.
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)
@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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.