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.

"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. 

import java.util.HashSet;

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

 public void setName(String name) { = name;
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + 
  ((name == null) ? 0 : name.hashCode());
  return result;

 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 ( != null)
    return false;
  } else if (!name.equals(
   return false;
  return true;


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

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


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


Recent Posts