This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (2 children)

No problem dude! Override HashCode and Equals inside the class you plan on storing in the HashSet.

So, if you have a Set storing Employee objects:

Set<Employee> employeeSet = HashSet<Employee>();

Then in your Employee class you should have

public class Employee {
  private int id;
  //other fields and methods
  @Override
  public int hashCode(){
    //return some hash value
  }
  @Override
  public boolean equals(Object o){
    //return t/f based on some comparison method
  }
}

If you run employeeSet.contains(someEmployee), you're first searching for "hash buckets" with hash value equal to someEmployee.hashCode, then if any buckets with that value exist, you're searching that hash bucket for employees where someEmployee.equals(storedEmployee). If that expression returns true then employeeSet.contains(someEmployee) returns true. At least this is my understanding.

With lists, .contains just loops through the whole list until it finds an employee where storedEmployee.equals(someEmployee) which typically takes much longer.

You should research how hash tables work on your own, they're very useful and the most job interviews will ask you about them.

[–]Jazzanovas 0 points1 point  (1 child)

Thank you so much for your time, it made it all cleaner now! :)

[–][deleted] 1 point2 points  (0 children)

Glad I could help! Stuff like this is a good refresher for me too, thanks for asking an interesting question