0

The equals() method

Please does anyone understand how this code works? @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Animal other = (Animal) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } Why the use of prime numbers and what is the equals method really doing?

7th Jun 2017, 1:25 PM
Daniel Graham
1 Réponse
+ 3
He's overriding the regular equals method so he can use it on his objects to compare equality. It first checks references, if the object isn't null/if the object is the object I'm comparing with. Then it checks the classes. I'd use instanceof instead 😝. I assume the class we're comparing extends animal, so an animal object is created. I suppose the animal class is what contains the name variable. name is a global instance variable in this object, so if it's null and the obj's name is not null, return false. If the names are not equal, return false. Otherwise, return true. It looks more complicated than it really is. For hashcode, there's a better explanation than one I can give here for why primes are used: https://stackoverflow.com/questions/3613102/why-use-a-prime-number-in-hashcode Returning true means the objects are considered equals.
7th Jun 2017, 2:05 PM
Rrestoring faith
Rrestoring faith - avatar