Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMatthew Francis
6,967 PointsNewbie - Why do we need to create hashCode() method when we create equals() method?
What is the purpose of creating hashCode() when we create the equals() method? and when the two methdos are created, what are they overriding?
equals() method:
public boolean equals(Object obj){
if(obj == null) return false;
if(!(obj instanceof Employee)) return false;
Employee other = (Employee) obj;
System.out.println(this.employeeId);
System.out.println(other.employeeId);
return this.employeeId == other.employeeId;
}
hashCode() method:
public int hashCode(){
final int PRIME = 31;
int result = 1;
result = PRIME * result + getId();
return result;
}
1 Answer
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 PointsCheck out this nice Stack discussion, look pretty self-explainable to me:
http://stackoverflow.com/questions/17027777/relationship-between-hashcode-and-equals-method-in-java