Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java AbstractSet hashCode() Method
Next article icon

Java AbstractSet hashCode() Method

Last Updated : 05 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The hashCode() method in AbstractSet (and its subclasses like HashSet) computes a hash code based on the elements of the set. It ensures that if two sets contain the same elements, their hash codes will be the same, provided the elements themselves return consistent hash codes.

Working of Hash Code:

  • The hashCode() of a set is computed as the sum of hash codes of all elements in the set.
  • The order of elements does not affect the hash code.
  • If two sets contain the same elements, their hash codes will be identical (as long as the elements' hash codes remain consistent).
  • A HashSet relies on both hashCode() and equals() to check for duplicate elements.

Example 1: This example demonstrates how to create a HashSet, add elements to it, and display its hash code.

Java
// Java program to display the hashcode of a set import java.util.HashSet; import java.util.Set;  public class Geeks {        public static void main(String[] args)     {         // Create three Set         Set<Integer> s1 = new HashSet<>();         s1.add(1);         s1.add(2);         s1.add(3);          System.out.println("Set1: " + s1);            // Displaying hash code         System.out.println("Hash code of set1: "                            + s1.hashCode());      } } 

Output
Set1: [1, 2, 3] Hash code of set1: 6 

Explanation: AbstractSet sums the hash codes of its elements:

hashCode = 1.hashCode() + 2.hashCode() + 3.hashCode()

= 1 + 2 + 3

= 6

Syntax of hashCode() Method

public int hashCode()

  • Parameter: This method does not take any parameter
  • Return Type: This method returns an integer value that represents the hash code of the object.

Example 2: This example demonstrates how hashCode and equals() work together to compare custom objects correctly and ensure they have same hash codes based on their properties.

Java
// Java program to demonstrates how hascode() works with // custom objects  import java.util.HashSet; import java.util.Objects;  class Person {     String name;     int age;      Person(String name, int age)     {         this.name = name;         this.age = age;     }      // Override hashCode()     @Override public int hashCode()     {         // Generates a hash code based on name and age         return Objects.hash(name, age);     }      // Override equals() to ensure consistency     @Override public boolean equals(Object o)     {         if (this == o)             return true;         if (o == null || getClass() != o.getClass())             return false;         Person person = (Person)o;         return age == person.age             && Objects.equals(name, person.name);     } }  public class HashCodeDemo {     public static void main(String[] args)     {         Person p1 = new Person("Alice", 30);         Person p2 = new Person("Alice", 30);         Person p3 = new Person("Bob", 25);          // Print hash codes         System.out.println("Hash code of p1: "                            + p1.hashCode());         System.out.println("Hash code of p2: "                            + p2.hashCode());         System.out.println("Hash code of p3: "                            + p3.hashCode());          // Check equality         System.out.println("p1 equals p2: "                            + p1.equals(p2));         System.out.println("p1 equals p3: "                            + p1.equals(p3));     } } 

Output
Hash code of p1: 1963862399 Hash code of p2: 1963862399 Hash code of p3: 2076901 p1 equals p2: true p1 equals p3: false 

Next Article
Java AbstractSet hashCode() Method

C

chinmoy lenka
Improve
Article Tags :
  • Misc
  • Java
  • Java-Collections
  • Java - util package
  • Java-Functions
  • java-hashset
  • Java-AbstractSet
Practice Tags :
  • Java
  • Java-Collections
  • Misc

Similar Reads

    Java HashSet
    HashSet in Java implements the Set interface of Collections Framework. It is used to store the unique elements and it doesn't maintain any specific order of elements. Can store the Null values.Uses HashMap (implementation of hash table data structure) internally.Also implements Serializable and Clon
    12 min read
    Java HashSet add() Method
    The HashSet add() method in Java is used to add a specific element to the set. This method will add the element only if the specified element is not present in the HashSet. If the element already exists, the method will not add it again. This method ensures that no duplicate elements are added to th
    2 min read
    Java HashSet clear() Method
    The clear() method of the HashSet class in Java is used to clear all the elements from the HahSet. This method makes the HashSet empty but does not delete the HashSet itself. It simply removes all elements, leaving the set ready for reuse.Syntax of HashSet clear() Methodvoid clear()Key Points:After
    1 min read
    Java HashSet contains() Method
    The contains() method of the HashSet class in Java is used to check if a specific element is present in the HashSet or not. So, mainly it is used to check if a set contains any particular element.Java// Java program to demonstrates the working of contains() import java.util.*; public class Geeks { p
    1 min read
    HashSet remove() Method in Java
    The HashSet remove() method in Java is used to remove a specific element from the set if it is present.Note: HashSet and the remove() were introduced in JDK 1.2 as part of the Collections Framework and are not available in earlier versions of Java (JDK 1.0 and JDK 1.1).Example 1: Here, the remove()
    2 min read
    Java HashSet iterator() Method
    The HashSet iterator() method in Java is used to return an iterator that can be used to iterate over the elements in a HashSet. HashSet does not maintain any specific order of its elements, so the elements are returned in random order when iterated over. The iterator() method provides a way to trave
    3 min read
    Java HashSet isEmpty() Method
    The HashSet isEmpty() in Java is used to check if the HashSet is empty or not.Syntax of HashSet isEmpty() Methodboolean isEmpty()Return Type: This method returns "true" if the HashSet is empty, otherwise returns "false".Example: This example demonstrates how the isEmpty() method checks whether the g
    1 min read
    Java HashSet size() Method
    The HashSet size() method in Java is used to get the size of the HashSet or the number of elements present in the HashSet. Syntax of HashSet size() Methodint size()Return Type: This method returns an integer value that represents the number of elements currently stored in the HashSet.Example: This e
    1 min read
    Java HashSet clone() Method
    The HashSet clone() method in Java is used to return a shallow copy of the given HashSet. It just creates a copy of the set.Syntax of HashSet clone() Methodpublic Object clone()Return Type: This method returns a new HashSet object that contains the same element as the original set.Example: This exam
    1 min read
    Java AbstractSet equals() Method
    The AbstractSet equals() Method in Java is used to check for equality between two sets. This method verifies whether the elements of one set are equal to the elements of another set.Syntax of AbstractSet equals() Methodpublic boolean equals(Object o)Parameter: The object "o" is to be compared for eq
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences