How does a HashSet work in Java


HashSet stores its elements in an array a such that a given element o is stored at index o.hashCode() % array.length. Any element in the set must be placed in one exact index of the array.


Example:
"Tom Katz".hashCode() % 10 == 6
"Sarah Jones".hashCode() % 10 == 8
"Tony Balognie".hashCode() % 10 == 9

Hence, an object will be considered to be in the set only if both:
  • It has the same hash code as an element in the set, and
  • The equals comparison returns true
An object that is put into a HashSet works best if it has a public int hashCode() method defined. 



Example:
import java.util.HashSet;

class Employee {
 String name;
 
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
 @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;
  Employee other = (Employee) obj;
  if (name == null) {
   if (other.name != null)
    return false;
  } else if (!name.equals(other.name))
   return false;
  return true;
 }

}

public class HashmapExample{
 public static void main(String[] args) {

  HashSet hs = new HashSet();
  Employee e1 = new Employee();
  e1.setName("Java");
  Employee e2 = new Employee();
  e2.setName("Java");
  System.out.println("e1 Hashcode=" + e1.hashCode());
  System.out.println("e1 Hashcode=" + e2.hashCode());
  hs.add(e1);
  hs.add(e2);
  System.out.println("HashSet Elements: "+hs);

 }

}
Output:
e1 Hashcode=2301537
e1 Hashcode=2301537
HashSet Elements: [Employee@231e61]

Search: