0
Can some explain this code to me please?
class Animal { String name; Animal(String n) { name = n; } @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; Ani
4 Answers
+ 9
Yes, hashCode belongs to object class, and equals too. Is recommended to overwrite them if you gonna use it.
hasCode is used to generate key values for hash data structures, like a hash table. It must return different values for each object with different attribute values.
equals is used to know if two objects have the same attribute values. If you use '==', it just compare object references.
Hope this make sense for you. ;)
+ 2
The explanation is added as comments. I hope it can be at least a little bit useful:
class Animal {
String name;
/*
simple constructor ~ assigning of name value (object of String)
*/
Animal(String n) {
name = n;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
/*
basically if the name is null (no object of string class is assigned to name) it counts result as :
prime*result (because result is 1 it can even be just prime)
is the name is not null it counts hash (result) as sum of prime*result + name.hashCode () (hashCode of name added with prime)
here the ternary operator is used instead of if statement (https://en.m.wikipedia.org/wiki/%3F:)
*/
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/*
here the function returns true, when object to be compared is the same ( it is the same instance of class)
when the object to compare is null (actually nothing) or is not of the same class, it returns false
( there is the case, when the object is of same class but not the exactly same instance, which is not considered )
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
0
is the name.Hashcode() a built in function belong to the object class?
0
thanks guys