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 trial

Java Local Development Environments Advanced Tooling Code Generation

Matthew Francis
Matthew Francis
6,967 Points

Newbie - 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